Surprisingly, time arithmetic is not handled as expected with pythons timezone aware objects. For example consider this
snippet that creates a timezone aware object at 2022-10-30 02:00.
from datetime import datetime, timezone, timedelta
from zoneinfo import ZoneInfo
zone = ZoneInfo("Europe/Madrid")
HOUR = timedelta(hours=1)
u0 = datetime(2022, 10, 30, 2, tzinfo=zone)
At 2:59 the clocks shifted back to 2:00, marking the ending of the daylight saving time period.
This makes 2022-10-30 02:00 ambiguous. In 2022-10-30 the clocks showed 2:00 twice. Fist comes the
DST instance 2022-10-30 02:00:00+02:00
followed by the winter time instance 2022-10-30 02:00:00+01:00
, when the timezone shifted from CEST to CET.
Python solves the ambiguity by selecting u0
to be the first of the two instances, the one within the DST
interval. This is verified by by printing out u0
and its timezone name:
>>> print(u0)
2022-10-30 02:00:00+02:00
>>> u0.tzname()
'CEST'
which is the central European daylight saving timezone.
If we add one hour to u0
, the passage to CET
, i.e. the winter timezone for central Europe, is correctly detected.
>>> u1 = u0 + HOUR
>>> u1.tzname()
'CET'
However, the time does not fold back to 2:00, as expected:
>>> print(u1)
2022-10-30 03:00:00+01:00
'CET'
So, with the addition of a 1h interval, it looks as if 2 hours have passed. One hour due to the wall time shifting from 2:00 to
3:00 and another one due to the change of the timezone that is shifted 1h towards UTC. Conversely one would expect u1
to print out as 2022-10-30 02:00:00+01:00
. This 2 hour shift is verified by converting u0
and u1
to UTC:
>>> u0.astimezone(timezone.utc)
datetime.datetime(2022, 10, 30, 0, 0, tzinfo=datetime.timezone.utc)
>>> u1.astimezone(timezone.utc)
datetime.datetime(2022, 10, 30, 2, 0, tzinfo=datetime.timezone.utc)
To make things worse, the time interval between u1
and u0
is inconsistently calculated depending on the
chosen timezone. On the one hand we have:
>>> u1 - u0
datetime.timedelta(seconds=3600)
which is equivalent to a 1h interval.
On the other hand, if we do the same calculation in UTC:
>>> u1.astimezone(timezone.utc) - u0.astimezone(timezone.utc)
datetime.timedelta(seconds=7200)
the calculated interval is 2h.
In conclusion, it appears that Python’s handling of timedelta in timezone-aware datetimes emphasizes local clock times rather than consistent logical intervals, leading to potential discrepancies when crossing DST boundaries.
In my opinion, this can be misleading, as the existence of the zoneinfo
library gives the impression that these kind of problems have
been solved.
Does
anyone know if this is a bug or expected behaviour? Has anyone else encountered this issue, and how do you manage these discrepancies in your applications? If this is expected behavior, perhaps Python documentation should provide clearer guidance or warnings about performing time arithmetic with timezone-aware objects.