Why a timezone aware datetime's tzinfo does not equal the timezone?

北城余情 提交于 2019-12-04 03:58:56

问题


>>> import pytz
>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False

What's the reason for these to differ?

>>> dt_aware.tzinfo
<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>
>>> tz
<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>

回答1:


The key that determines the timezone from pytz is the string you passed to create the object: 'America/Chicago'. That key is available through the .zone attribute.

>>> tz = pytz.timezone('America/Chicago')
>>> dt_naive = datetime(year=2017, month=6, day=6)
>>> dt_aware = tz.localize(dt_naive)
>>> dt_aware.tzinfo == tz
False
>>> tz.zone
'America/Chicago'
>>> dt_aware.tzinfo.zone == tz.zone
True



回答2:


The first one has been adjusted to the date and time provided, 2016-06-06T00:00:00. Central Daylight Time (CDT) is in effect at this time. It is 5 hours behind UTC (24:00 - 05:00 = 19:00).

The second one has not been localized, so it is giving you the first offset in the available time zone data, which happens to be the Local Mean Time (LMT) entry. You can see this in the tzdata sources here. The LMT is 5 hours, 50 minutes, and 36 seconds behind UTC. The seconds of the LMT offset are rounded off somewhere in pytz, so 18:09 is reflecting this correctly (24:00 - 05:51 = 18:09)



来源:https://stackoverflow.com/questions/44397094/why-a-timezone-aware-datetimes-tzinfo-does-not-equal-the-timezone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!