So... just confirmed an already-reported bug in #Python that some on here may be interested to know about. In at least 3.11 and probably 3.9-3.12+, adding or subtracting datetime.datetime objects which are time-zone-aware and have the same tzinfo will give incorrect results when crossing a time shift in their time zone.
For example, there's a fall-back shift on November 3rd this year in the Eastern US time zone, from EDT (Eastern Daylight Time) to EST (Eastern Standard Time). The zoneinfo module can represent this time zone if you say zoneinfo.ZoneInfo('America/New_York') and you have IANA time zone files on your system (IIRC Windows doesn't). At 1 a.m. on 2024-11-3, an hour repeats, first in EDT and then in EST. Python can represent the repeated hour and convert times from/to UTC mostly correctly, but will give incorrect results when e.g. adding across the transition. For example, 2024-11-03T00:45 EDT plus 1 hour is 2024-11-03T01:45 EDT which python gets right. But plus 2 hours should be 2024-11-03T01:45 E*S*T, which python gets wrong (it returns 2024-11-03T02:45 EST, which is 2 hours later, not 1.
Similarly, subtracting 2024-11-2T00:00 EDT from 2024-11-4T00:00 EST should give a difference of 2 days and 1 hour, but python gives 2 days exactly (it does work correctly if you give the time zones as UTC offsets, but not if you use the same tzinfo object).
Time math is incredibly cursed (see above) so I don't blame the Python devs for this, but I do hope it will get fixed.
My guess is that the code checks if the tzinfo objects are the same and then does simple math if they are, when instead it should have checked whether their utfoffset results were the same. Gotta think whether I have the time to submit a PR for this...
Tom Ritchford
in reply to Tiota Sram • • •Quibble: you can't add two datetime objects! 😀
Thanks for doing this, you'll probably save someone considerable time.
The issue is here: https://github.com/python/cpython/issues/116111
I think I saw this on the Python list earlier this year...
datetime arithmetic during DST transitions is incorrect · Issue #116111 · python/cpython
GitHub