I need to compare pytz.timezone
s for equality, and the behavior I'm observing is quite unintuitive.
I've read a lot about Python time zones, pytz
, zoneinfo
, LMT, etc., both on SO and generally on the web. The behavior I'm concerned about does not seem to be obviously related to the typical concerns people have with pytz
and solved similarly. The only workaround I've found is comparing the pytz.timezone.zone
strings, which is clunky.
The two examples below show the pytz.timezone
comparison behavior. Used: Python==3.9, pytz==2022.2.1, pandas==1.5.3. The behavior of zoneinfo.ZoneInfo
objects is, in contrast, sane and intuitive.
Example 1, LMT:
>>> tz = pytz.timezone("America/Chicago")
>>> tz
<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD>
>>> tz.localize(datetime.now()).tzinfo == tz
False
>>> pd.DataFrame({'t': [tz.localize(datetime.now())]}).t.dt.tz == tz
True
>>> pd.DataFrame({'t': [tz.localize(datetime.now())]}).t.dt.tz_convert(tz).dt.tz == tz
True
Example 2, CST:
>>> tz = pytz.timezone("America/Chicago").localize(datetime.now()).tzinfo
>>> tz
<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>
>>> tz.localize(datetime.now()).tzinfo == tz
True
>>> pd.DataFrame({'t': [tz.localize(datetime.now())]}).t.dt.tz == tz
False
>>> pd.DataFrame({'t': [tz.localize(datetime.now())]}).t.dt.tz_convert(tz).dt.tz == tz
False
I expect no False
comparisons above, which is exactly what I get if I use zoneinfo
instead.