I have this code:
import datetime
import dateutil.tz
tz = dateutil.tz.gettz('America/New_York')
dt_before = datetime.datetime(2022, 3, 13, 1, 30, tzinfo=tz)
dt_after = datetime.datetime(2022, 3, 13, 3, 30, tzinfo=tz)
In this code, dt_before is 1:30 AM EST on 2022-03-13, and dt_after is 3:30 AM EDT on 2022-03-13. These times are exactly 1 hour apart due to the daylight savings time shift between them.
However, if I add 1 hour to dt_before, I get 2:30 AM, which doesn't exist on that day. The result is not equal to dt_after.
>>> dt_before + datetime.timedelta(hours=1)
datetime.datetime(2022, 3, 13, 2, 30, tzinfo=tzfile('/usr/share/zoneinfo/America/New_York'))
>>> dt_before + datetime.timedelta(hours=1) == dt_after
False
In fact, the following evaluates to True, which is bonkers:
>>> dt_before + datetime.timedelta(hours=1) == dt_after - datetime.timedelta(hours=1)
True
How can I correctly add and subtract timedeltas to/from datetimes using dateutil.tz?
The exact same issue happens with the zoneinfo library introduced in Python 3.9; just initialize tz as tz = zoneinfo.ZoneInfo('America/New_York') above.