用python获取当前时间
时间: 2023-11-26 15:02:01 浏览: 79
可以使用Python内置模块`datetime`来获取当前时间。
示例代码:
```python
import datetime
# 获取当前时间
now = datetime.datetime.now()
# 输出当前时间
print("当前时间为:", now)
```
输出结果:
```
当前时间为: 2022-03-16 20:34:59.123456
```
其中,`now()`函数返回的是一个`datetime`对象,包括年、月、日、时、分、秒、微秒等信息。如果只需要获取当前时间的某个部分,可以使用`year`、`month`、`day`、`hour`、`minute`、`second`等属性进行访问。例如:
```python
# 获取当前年份
year = now.year
print("当前年份为:", year)
# 获取当前月份
month = now.month
print("当前月份为:", month)
# 获取当前日
day = now.day
print("当前日为:", day)
# 获取当前小时
hour = now.hour
print("当前小时为:", hour)
# 获取当前分钟
minute = now.minute
print("当前分钟为:", minute)
# 获取当前秒数
second = now.second
print("当前秒数为:", second)
# 获取当前微秒数
microsecond = now.microsecond
print("当前微秒数为:", microsecond)
```
输出结果:
```
当前年份为: 2022
当前月份为: 3
当前日为: 16
当前小时为: 20
当前分钟为: 34
当前秒数为: 59
当前微秒数为: 123456
```
阅读全文