在下面的代码中:
from datetime import datetime
import pytz
EDT = pytz.timezone('US/Eastern')
d1 = datetime.now(tz=EDT)
d2 = datetime.combine(d1.date(), d1.time(), tzinfo=EDT)
为什么 d1 和 d2 显示不同的时区信息?
>> d1
datetime.datetime(2021, 4, 8, 7, 0, 44, 316514, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)
>> d2
datetime.datetime(2021, 4, 8, 7, 0, 44, 316514, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)
如何在使用 datetime.combine
时获得与 datetime.now
相同的日期时间?
最佳答案
datetime.now
使用 pytz
时区对象有效地转换(本地化)您的日期时间 - 来自 docs :
If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz’s time zone.
datetime.combine不会那样做。这就好像你会写类似 datetime(2020,1,1, tzinfo=pytz.timezone('US/Eastern'))
的东西 - 实际上 不调整时间区域到提供的日期/时间。另见例如pytz localize vs datetime replace和 pytz: The Fastest Footgun in the West了解更多背景信息。
使用 pytz
获取 d2
的正确方法是
d2 = EDT.localize(datetime.combine(d1.date(), d1.time()))
如果使用 dateutil
或 zoneinfo
(Python 3.9+) 中的时区对象,则不会出现此类问题:
from datetime import datetime
from zoneinfo import ZoneInfo
EDT = ZoneInfo('US/Eastern')
d1 = datetime.now(tz=EDT)
d2 = datetime.combine(d1.date(), d1.time(), tzinfo=EDT)
# d1
# Out[75]: datetime.datetime(2021, 4, 8, 7, 57, 18, 309209, tzinfo=zoneinfo.ZoneInfo(key='US/Eastern'))
# d2
# Out[76]: datetime.datetime(2021, 4, 8, 7, 57, 18, 309209, tzinfo=zoneinfo.ZoneInfo(key='US/Eastern'))
# d1 == d2
# Out[77]: True
关于python - datetime.combine with timezone 不同于 datetime.now with timezone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67002702/
相关文章:
java - 在 Spring Cloud Gateway 中获取真实的客户端 IP 地址
typescript - 类型错误 : Property 'currentTime' does no
sql-server - SQL 服务器 : splitting a row into severa
ios - FaSTLane 设置 - 致命 : could not read Password f
mongodb - 如何在 Rust 中使用 Mongodb::cursor?
azure - 对于高级、低延迟、带有搜索功能的大量小型 json 文件,Azure BlockBl
javascript - 如果没有 .js 扩展名,则为 ERR_MODULE_NOT_FOUND