Python datetime 模块

Python datetime.now() 函数用于返回当前本地时间

语法

datetime.now()
datetime.now(tz)

参数

可选 tz:时区对象。省略则返回本地时间。

返回值

返回当前时间的 datetime 对象,可访问 year/month/day/hour 等属性。

示例

from datetime import datetime

now = datetime.now()
print(now)                      # 2024-01-15 10:30:45.123456
print(now.year, now.month, now.day)   # 2024 1 15
print(now.hour, now.minute, now.second)
print(now.weekday())            # 0~6,周一为0

# 获取 UTC 时间
from datetime import timezone
print(datetime.now(timezone.utc))

注意事项

now() 是本地时间,不同时区结果不同。要 UTC 用 now(timezone.utc)。