stub42/pytz

tzinfo equality

leaver2000 opened this issue · 0 comments

pytz.timezones equality does not evaluate to true when comparing against their standard lib counterparts.

>>> import datetime
>>> import pytz
>>> dt_1 = datetime.datetime(2023, 1, 1, tzinfo=datetime.timezone.utc)
>>> dt_2 = datetime.datetime(2023, 1, 1, tzinfo=pytz.UTC)
>>> dt_1 == dt_2
True
>>> dt_1.tzinfo == dt_2.tzinfo
False

I ran into this with some unit test and json decoding with pandas.to_datetime where pytz.UTC is used.

>>> def is_utc(obj:datetime.datetime) -> bool:
...     return obj.tzinfo == datetime.timezone.utc
... 
>>> is_utc(dt_1)
True
>>> is_utc(dt_2)
False

Below is the work around I have implemented.

>>> class UniversalTimeCoordinate(type(pytz.UTC)):
...     def __eq__(self, o) -> bool:
...         return o == pytz.UTC or o == datetime.timezone.utc
... 
>>> UTC = UniversalTimeCoordinate()
>>> dt_3 = datetime.datetime(2023, 1, 1, tzinfo=UTC)
>>> dt_3.tzinfo == dt_2.tzinfo
True
>>> dt_3.tzinfo == dt_1.tzinfo
True
>>> is_utc(dt_3)
True
>>> dt_3 == dt_2 == dt_1
True
>>>