Python获取当前时间的方法
时间: 2023-11-05 11:58:23 浏览: 73
获取当前时间的方法可以使用Python内置的datetime模块,具体步骤如下:
1. 导入datetime模块
```python
import datetime
```
2. 使用datetime模块的now()函数获取当前时间
```python
now = datetime.datetime.now()
```
3. 可以使用strftime()函数将时间格式化成字符串格式
```python
time_str = now.strftime('%Y-%m-%d %H:%M:%S')
```
完整代码如下:
```python
import datetime
now = datetime.datetime.now()
time_str = now.strftime('%Y-%m-%d %H:%M:%S')
print("当前时间为:", time_str)
```
输出结果类似于:
```
当前时间为: 2021-09-20 14:30:00
```
相关问题
python获取当前时间
可以使用Python的datetime模块来获取当前时间。具体代码如下:
```python
import datetime
now = datetime.datetime.now()
print("当前时间为:", now)
```
输出结果类似于:
```
当前时间为: 2021-10-16 17:34:12.123456
```
其中,now()函数返回的是一个datetime对象,包含当前的日期和时间信息。你可以根据自己的需求来格式化输出的时间信息。
python 获取当前时间
要在Python中获取当前时间,你可以使用`datetime`模块。具体方法是使用`datetime`模块的`datetime`类,并调用其`now()`方法来获取当前时间。
下面是一个示例代码,演示如何获取当前时间:
```python
from datetime import datetime
# 获取当前时间
current_time = datetime.now()
# 打印当前时间
print(current_time)
```
上述代码将打印出当前的日期和时间,格式类似于`2022-01-01 10:30:00.123456`。
你也可以使用`strftime()`方法来格式化输出的时间,以满足你的需求。例如,如果你只想获取当前时间的小时和分钟,可以使用以下代码:
```python
current_time = datetime.now().strftime("%H:%M")
print(current_time)
```
上述代码将打印出当前时间的小时和分钟,格式类似于`10:30`。
希望能对你有所帮助!如果你还有其他问题,请随时提问。
阅读全文
相关推荐











