📜  datetime 现在带有时区 (1)

📅  最后修改于: 2023-12-03 15:30:23.013000             🧑  作者: Mango

Python中的 datetime 现在带有时区

在 Python 中,datetime 类型可以用来表示日期和时间。自 Python 3.2 起,datetime 类型加入了对时区的支持,使得程序员可以更加方便地处理时间和日期。

要使用 datetime 中的时区功能,需要先导入 datetime 模块中的 timezone 类型:

from datetime import datetime, timezone

使用 datetime 的 now 方法获取当前时间,并将其转换为指定时区的时间:

now = datetime.now(timezone.utc)

这样就获取了当前时间的 UTC 标准时间。我们还可以指定其他时区:

now = datetime.now(timezone(timedelta(hours=8))) # 北京时间
now = datetime.now(timezone(timedelta(hours=-5))) # 纽约时间

除了 now 方法外,我们还可以使用 fromtimestamp 方法将时间戳转换为指定时区的时间:

timestamp = 1609459200 # 2021年1月1日 00:00:00 UTC
dt = datetime.fromtimestamp(timestamp, timezone.utc)

最后,我们可以使用 strftime 方法将 datetime 对象格式化为字符串:

dt_str = dt.strftime("%Y-%m-%d %H:%M:%S %Z")
print(dt_str) # 2021-01-01 00:00:00 UTC

以上就是 Python 中 datetime 现在带有时区的介绍,希望能对你有所帮助!