Why are these not equal?
>>> from datetime import datetime>>> from datetime import timedelta>>> from datetime import timezone>>> from zoneinfo import ZoneInfo>>> from zoneinfo import ZoneInfoNotFoundError>>> dt_tz = datetime.now(tz=timezone.utc)>>> dt_zi = dt_tz.astimezone(tz=ZoneInfo("UTC"))>>> dt_tzdatetime.datetime(2024, 5, 1, 23, 15, 24, 3560, tzinfo=datetime.timezone.utc)>>> dt_zidatetime.datetime(2024, 5, 1, 23, 15, 24, 3560, tzinfo=zoneinfo.ZoneInfo(key='UTC'))>>> dt_tz == dt_ziTrue>>> dt_tz.tzinfo == dt_zi.tzinfoFalseHow is it possible to check that two datetime tz-aware objects have an equivalent TZ, if they are created with either timezone or ZoneInfo? At first sight, these things intend to do the same stuff but they are not entirely inter-operable. For example, there is no ZoneInfo.astimezone() conversion.
In anticipation of answers that recommend using some third-party library, those answers are OK but the strong preference is to use python builtin packages (python 3 >= 3.11).
One Approach
>>> dt_tz.tzname()'UTC'>>> dt_zi.tzname()'UTC'>>> dt_tz.tzname() == dt_zi.tzname()True>>> dt_tz.tzinfodatetime.timezone.utc>>> type(dt_tz.tzinfo)<class 'datetime.timezone'>>>> ZoneInfo(dt_tz.tzname())zoneinfo.ZoneInfo(key='UTC')BUT this doesn't generalize beyond UTC :(
>>> dt_ny = datetime.now().astimezone(ZoneInfo("America/New_York"))>>> dt_nydatetime.datetime(2024, 5, 1, 19, 38, 53, 69087, tzinfo=zoneinfo.ZoneInfo(key='America/New_York'))>>> ts = dt_ny.isoformat()>>> ts'2024-05-01T19:38:53.069087-04:00'>>> ts_dt = datetime.fromisoformat(ts)>>> ts_dtdatetime.datetime(2024, 5, 1, 19, 38, 53, 69087, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))>>> ts_dt.tzname()'UTC-04:00'>>> ZoneInfo(ts_dt.tzname())zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key UTC-04:00'