为什么时区感知日期时间的 tzinfo 不等于时区?

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

>>> 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

这些不同的原因是什么?

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

第一个已调整为提供的日期和时间,2016-06-06T00:00:00。中部夏令时 (CDT) 此时有效。比 UTC 晚 5 小时 (24:00 - 05:00 = 19:00)。

第二个尚未本地化,因此它为您提供了可用时区数据中的第一个偏移量,恰好是 Local Mean Time (LMT) entry. You can see this in the tzdata sources here。 LMT 比 UTC 晚 5 小时 50 分 36 秒。 LMT 偏移量的秒数在 pytz 中的某处四舍五入,因此 18:09 正确反映了这一点 (24:00 - 05:51 = 18:09)

pytz 确定时区的关键是您传递给创建对象的字符串:'America/Chicago'。该密钥可通过 .zone 属性获得。

>>> 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