Skip to content

tzinfo equality #103

Description

@leaver2000

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

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions