Skip to content

datetime arithmetic during DST transitions is incorrect #116111

In progress

Description

@cjw296

Bug description:

While working on a followup to #116035, given:

>>> from datetime import datetime, timedelta
>>> from zoneinfo import ZoneInfo
>>> t = datetime(2024, 10, 27, 1, tzinfo=ZoneInfo('Europe/London'), fold=0)
>>> str(t)
'2024-10-27 01:00:00+01:00'
>>> t2 = t + timedelta(minutes=30)
>>> t2
datetime.datetime(2024, 10, 27, 1, 30, tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))
>>> str(t2)
'2024-10-27 01:30:00+01:00'

I noticed this buggy behaviour:

>>> t3 = t + timedelta(minutes=60)
>>> str(t3)
'2024-10-27 02:00:00+00:00'
>>> t3
datetime.datetime(2024, 10, 27, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))

The correct answer would be:

>>> datetime(2024, 10, 27, 1, tzinfo=ZoneInfo('Europe/London'), fold=1)
datetime.datetime(2024, 10, 27, 1, 0, fold=1, tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))
>>> str(datetime(2024, 10, 27, 1, tzinfo=ZoneInfo('Europe/London'), fold=1))
'2024-10-27 01:00:00+00:00'

Similarly, given:

>>> t1 = datetime(2024, 3, 31, 0, tzinfo=ZoneInfo('Europe/London'))
>>> t1
datetime.datetime(2024, 3, 31, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))
>>> str(t1)
'2024-03-31 00:00:00+00:00'

This is incorrect:

>>> t2 = t1 + timedelta(minutes=60)
>>> t2
datetime.datetime(2024, 3, 31, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/London'))
>>> str(t2)
'2024-03-31 01:00:00+00:00'

The above point in time doesn't exist, it should be:

>>> str(datetime(2024, 3, 31, 2, 0, tzinfo=ZoneInfo(key='Europe/London')))
'2024-03-31 02:00:00+01:00'

CPython versions tested on:

3.12

Operating systems tested on:

No response

Linked PRs

Activity

  1. added
    type-bug
    on Feb 29, 2024
  2. changed the title [-]datetime arithmetic during DST folds is incorrect[/-] [+]datetime arithmetic during DST transitions is incorrect[/+] on Feb 29, 2024
  3. cjw296 commented on Feb 29, 2024

    @cjw296
    ContributorAuthor

    #116038 probably related...

  4. solsword commented on Aug 6, 2024

    @solsword

    Can confirm this, and it's most pressing when it gives invalid timedelta results for datetimes across a transition boundary.

    Here's an example of how things break BOTH when using fold and even when not using fold:

    import datetime, zoneinfo
    
    
    z = zoneinfo.ZoneInfo('America/New_York')  # EST and EDT, depends on date
    
    # 15 min before "fall-back", still on Eastern Daylight Time
    d1 = datetime.datetime(2024, 11, 3, 0, 45, tzinfo=z)
    assert d1.strftime('%Z') == 'EDT'
    
    # default fold = 0, 1 hour after d1, still on EDT
    d2 = datetime.datetime(2024, 11, 3, 1, 45, tzinfo=z)
    assert d2.strftime('%Z') == 'EDT'
    
    # explicit fold = 1, 2 hours after d1, now on EST
    d3 = datetime.datetime(2024, 11, 3, 1, 45, tzinfo=z, fold=1)
    assert d3.strftime('%Z') == 'EST'
    
    # default fold = 0 (and fold cannot be 1), after fall-back transition
    # this time occurs 3 hours after d1, not 2 hours as the 'hours' might
    # seem to indicate.
    d4 = datetime.datetime(2024, 11, 3, 2, 45, tzinfo=z)
    assert d4.strftime('%Z') == 'EST'
    
    print('Should be 1 hour:', d3 - d1)
    assert (d2 - d1) == datetime.timedelta(hours=1)
    print('Should be 2 hours:', d3 - d1)
    assert (d3 - d1) == datetime.timedelta(hours=2)  # fails due to bug
    print('Should be 3 hours:', d4 - d1)
    assert (d4 - d1) == datetime.timedelta(hours=3)  # fails due to bug

    I'm guessing the code does something like "if time zones are the same, then we can just subtract numbers directly without worrying about time zones, hooray" which works for simple constant-offset time zones as originally available, but with the introduction of zoneinfo and zones that actually have transitions, this fails. I cannot imagine why this wasn't already a test case...

    If this is really intended behavior, then at minimum there needs to be a warning in the timedelta section of the datetime module, stating that timedelta objects created by subtracting two datetimes on different sides of a time zone transition will be incorrect. Similarly, adding a timedelta to a time-zone-aware datetime gives incorrect results across date transitions (try d1 + datetime.timedelta(hours=3) above and you get a time that's 4 hours later.

    Quoting from the other bug linked here:

    As always, if you want time zone to matter, you need to convert between time zones (typically to UTC, do computation there, and then convert back).

    So, that's great info for me to have now, but I sure wish I had learned that after carefully reading the docs for timedelta and datetime regarding tzinfo (but not focusing on astimezone which I'm not using in this code). I hope that while this gets triaged and hopefully fixed in a future release, we can get a docs update with a bright warning about timedeltas being wrong on time-zone-aware datetimes across time shifts. Preferably, this would be mentioned in at least three places: near the top of the timedelta section of the datetime docs, in the table of timedelta operations as a footnote for any affected operations (at lesat + and -), and in the datetime section of the docs where tzinfo is discussed, noting that adding it may break timedelta results. It is at least good that Python already forbids subtracting aware and naive datetimes!) There are a LOT of ways this can come up even for people who don't think they're dealing with edge cases (e.g., subtracting two dates in different months to get a timedelta between them will be off by an hour if those months straddle a time zone shift, or shifting from tzinfo=datetime.UTC to tzinfo=zoneinfo.ZoneInfo('EST') will cause timedelta errors even though the objects were time-zone-aware both before and afterwards).

    IMO a simple-ish but perhaps non-performant fix would be to convert internally to UTC and then back when doing any timdelta stuff with time-zone-aware datetime.

    Apologies for the somewhat frustrated tone here... I've now spent a good few hours on tracking down why my time-zone-edge test cases weren't working, and it's disappointing to find that the "batteries included" here are broken. I know this stuff is really hard work and I appreciate the immense effort involved with upgrading to support fold= and the zoneinfo module. Writing code involving time is always a nightmare if you care about the edge cases :(

  5. cjw296 commented on Aug 6, 2024

    @cjw296
    ContributorAuthor

    @tim-one will be by shortly to explain why this is working as intended ;-)
    (he'll be right, I'm sure, but timezones are evil, so I'm sorry you're suffering too)

  6. solsword commented on Aug 9, 2024

    @solsword

    As I alluded to in my comment, I think that if the code part is "working as intended" then there's a documentation bug. FWIW given how evil time zones are I don't mind too much if the answer here is "programmer is responsible for converting to UTC and back if they want time-zone-aware math to work correctly" but I do mind if there is not any documentation of that fact in the relevant places.

  7. sauerburger commented on Sep 7, 2024

    @sauerburger

    I also painfully discovered this bug. I flipped flopped between "it's a bug" and "it's the intended behavior just not documented properly", however, the following code convinced that this cannot be intentional.

    Berlin and Paris share the same time, DST switching is identical.

    >>> from zoneinfo import ZoneInfo
    >>> from datetime import datetime
    
    >>> berlin = ZoneInfo("Europe/Berlin")
    >>> paris = ZoneInfo("Europe/Paris")
    
    >>> # Saturday evening before the upcoming DST switch
    >>> sat_berlin = datetime(2024, 10, 26, 21, 0, tzinfo=berlin)
    >>> sat_paris = datetime(2024, 10, 26, 21, 0, tzinfo=paris)
    
    >>> # Sunday morning after the upcoming DST switch
    >>> sun_berlin = datetime(2024, 10, 27, 9, 0, tzinfo=berlin)
    
    >>> sat_berlin.isoformat()
    2024-10-26T21:00:00+02:00  # +2 is fine, it's the DST
    
    >>> sat_paris.isoformat()
    2024-10-26T21:00:00+02:00  # Same here
    
    >>> sun_berlin.isoformat()
    2024-10-27T09:00:00+01:00  # +1 is fine, it's the STD
    
    >>> sun_berlin - sat_berlin
    datetime.timedelta(seconds=43200)  # 12h, NOT what a person with a stop watch would measure
    
    >>> sun_paris - sat_berlin
    datetime.timedelta(seconds=46800)  # 13h, correct

    @solsword

    I'm guessing the code does something like "if time zones are the same, then we can just subtract numbers directly without worrying about time zones, hooray"

    My example supports this. Berlin DST and Berlin STD are the same timezone object but don't share the same offset to UTC. Berlin DST and Paris STD are different timezone objects and datetime/zoneinfo do proper conversions.

    The current zonetime docs, say

    Datetimes constructed in this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention [...]

    but that's simply not true. I think it's hard to argue that this is the intended behavior.

  8. sauerburger commented on Sep 7, 2024

    @sauerburger

    The culprit in my view is this if-block that skips comparing UTC offset:

    if self._tzinfo is other._tzinfo:

           if self._tzinfo is other._tzinfo:
                return base
            myoff = self.utcoffset()
            otoff = other.utcoffset()
            if myoff == otoff:
                return base
            if myoff is None or otoff is None:
                raise TypeError("cannot mix naive and timezone-aware time")
            return base + otoff - myoff

    If there is consensus that it should be changed, but there is lack of person power, I'm more than happy to contribute a PR with a fix and tests.

  9. added
    stdlib
    extension-modules
    on Sep 7, 2024
  10. tim-one commented on Sep 7, 2024

    @tim-one
    Member

    It's entirely intended that, within a time zone (including the cases where binary operations are given datetime objects with the same (is) tzinfo object), arithmetic is done in "naive time": the tzinfo object(s) has/have no effect on the outcome.

    And it's always been intended that applications that want timezone-aware arithmetic need instead to convert to a common fixed-offset zone (like UTC) first, do arithmetic within that zone, and convert back to the desired zone after.

    That may not be the default behavior you want, but it's what Guido wanted 😉, and so that's how it's worked since the start.

    IMO, the docs could be made clearer about this. But it's far too late to change the design.

  11. added
    docs
    and removed
    type-bug
    stdlib
    extension-modules
    on Sep 8, 2024
  12. picnixz commented on Sep 8, 2024

    @picnixz
    Member

    Thank Tim for explaining the rationale. As such, I'm converting the issue into a docs issue where a PR is welcomed. Such PR would provide an utility function of how to do the arithmetic correctly (if none already exists) (a comment in the code base would be welcomed as well for not forgetting about the design choice).

  13. solsword commented on Sep 8, 2024

    @solsword

    I don't really like the "far too late to change the design" logic since the design has already changed significantly from what was first implemented (e.g., addition of the 'fold' mechanism) and since this is a straightforward improvement that involves commenting out two lines of code to eliminate behavior which probably leads to rarely-triggered (and thus hard-to-discover) bugs in a huge number of uses of time-zone-aware datetimes. As I said up-thread, at minimum there should be a docs change here.

    The one legitimate concern I can see is that getting rid of the tzinfo equality check makes all subtractions slower, even for naive datetimes. I think it would be worth profiling exactly how much slower it ends up, since you end up having to call utcoffset twice but that's it. An alternative would be to add an "accuratedatetime" subclass that just overrides sub (and any other affected methods) with the slower but actually accurate-in-all-cases version. That way people can opt-in to the correct behavior easily.

    The default behavior here is an absolute land-mine with potential security implications anywhere someone is using datetime with time-zones. It means that math on datetime objects works 99% of the time, but fails 1% of the time giving an incorrect result, and only if the programmer is sharp enough to test across DST transitions with identical time-zone objects will they actually discover this. Especially in a system with user-supplied time zones, I imagine this bug is affecting end-users all over the world right now, where their logic is just subtly off every time a transition happens (for me, it would have been all my student deadlines are potentially 1-hour wrong when DST starts or ends, since I was planning to let both students & professors specify their time zones, so I'd end up doing submission time - deadline likely in the same time zone).

    Just saying "sorry, don't ever subtract time-zone-aware datetime objects without converting them to something like UTC" which is what we currently do seems incredibly silly when 2 lines of code would make this just work. Actually saying that in all the relevant places in the docs would be one fix here, but I'd really like to see at least a subclass provided that's slightly slower (not sure how much) but actually does the right thing, so programmers can opt-in to the correct behavior. Even that seems like bad design to me: "welcome to Python, here's why not to use datetime.datetime unless you extremely care about speed." But it's a better compromise than just a docs update in my mind.

  14. tim-one commented on Sep 8, 2024

    @tim-one
    Member

    Adding fold repaired a fundamental problem: without it, it was flatly impossible to guarantee faithful roundtrip inter-zone conversions in all cases.

    The current behavior of intra-zone arithmetic cannot be changed. What you view as "a bug" was viewed by Guido as "a feature", deliberately intended, and catering to what a great many programmers actually want: if it's 2PM now, and they add "a day", they want "2PM tomorrow". They absolutely do not want 1PM - or 3PM - instead, depending on which time zone they happen to be working in, and on which day they happen to do the addition.

    A fancier design could cater to both kinds of meanings for intra-zone arithmetic, but operators like + have to pick a single meaning. "Naive time" is what they picked from the start. For inter-zone arithmetic, the concept of "naive time" doesn't really make sense, so arithmetic there effectively does the "convert to UTC, do arithmetic, convert back" dance under the covers.

    If you have a coherent alternative design, which preserves backward compatibility (dead on arrival if it doesn't), you can advocate for it on https://discuss.python.org/c/ideas/6, and/or write a PEP. The issue tracker isn't appropriate for design debates.

    Note: speed of arithmetic isn't a major issue here. datetime was designed primarily to make field extraction (what's the year? the month? the day? the hour? ...) as fast as possible. If speed of arithmetic mattered much, then, e.g. datetimes would have been stored instead as a 64-bit count of microseconds since datetime.datetime.min. Speed of arithmetic played scant role in the design. "Naive time" was Guido's intuition for what most programmers would find least surprising for intra-zone arithmetic.

    I expect he was right about that. There have been few complaints about it over the years. But the people who hate it, as you do, are extremely annoyed by it. That's regrettable, but default behavior won't be changed. You'll either have to live with it, or advocate for a fancier design via a more formal process.

  15. sauerburger commented on Sep 8, 2024

    @sauerburger

    @tim-one First of all, thank you for engaging in this discussion. I really appreciate that.

    The current behavior of intra-zone arithmetic cannot be changed. What you view as "a bug" was viewed by Guido as "a feature", deliberately intended, and catering to what a great many programmers actually want: if it's 2PM now, and they add "a day", they want "2PM tomorrow". They absolutely do not want 1PM - or 3PM - instead, depending on which time zone they happen to be working in, and on which day they happen to do the addition.

    I've read that argument before, but I honestly don't understand how this supports the current behavior. Of course: 2 pm + 1 day -> 2 pm, I fully agree. However, that's not the same operation as 2 pm + 24 hours. Depending on DST, +24hours might lead to 3pm or 1pm. I thought that's the whole point behind timedelta storing days and seconds separately, but I learned that’s not how it works. (BTW that’s the approach implemented in pendulum.)


    Besides the discussion on the design:

    To summarize, the recommended approach is: If one needs datetime arithmetics with timezones and DST taken into account, it’s necessary to convert all datetimes to UTC, perform the arithmetic, and then convert back. Right? This needs to be in the docs!

    The Python docs are surprisingly silent on the issue. I’ve found the following as a note to the arithmetics operation

    If both are naive, or both are aware and have the same tzinfo attribute, the tzinfo attributes are ignored, and the result is a timedelta object t such that datetime2 + t == datetime1. No time zone adjustments are done in this case.

    That’s precisely the behavior that you describe. In my view, this needs to be displayed in a prominent place with a warning that all arithmetics with TZ and DST should be done in UTC. I don’t want to speak for others, but I think most people are surprised to find out that there is difference between inter- and intra-timezone arithmetics. The docs introductions the difference between naive and aware date time but is silent on the intra- vs inter difference. Mixing naive and aware raises an exception, so devs cannot miss that point. The intra- vs inter difference is very easy to miss.

    Even worse, the zone info docs say

    Datetimes constructed in this way are compatible with datetime arithmetic and handle daylight saving time transitions with no further intervention [...]

    That's misleading at best. It’s actually a surprise to me if devs know about the difference between intra- and inter timezone operations.

  16. tim-one commented on Sep 8, 2024

    @tim-one
    Member

    days=1 and hours=24 mean exactly the same thing to a timedelta() constructor. You would need a different type of time delta object to capture any distinction. The internal representation is irrelevant to any of this; Guido's choice of internal "days", "seconds", and "microseconds" units was essentially arbitrary, and has no effect on semantics, just on the string representation.

    I coded almost all of the datetime implementation, so you can trust me on that 😉. But the docs are written in "reference manual" style. I've long agreed they could greatly benefit from a more tutorial-style addition spelling out the sometimes subtle consequences. But I'm too close to the code to write such a thing: it needs someone who's actually fought their way to an understanding. I'm so close that almost everything about it "is obvious" to me; it was thoroughly internalized years & years ago; nothing surprises me.

    I had nothing to do with the later "zone info", though, apart from endorsing the idea, and never even looked at its docs. I agree the part you quoted is misleading at best.

    In short, I can speak to how it is and how it got that way, but it's not an area I work in anymore. I'm just another datetime user now. And a happy one 😄.

  17. brownan commented on Oct 21, 2024

    @brownan

    I appreciate that there are different interpretations on how datetime math should work, and that the one that was chosen is what we have to stick with for historical design reasons. I'd just like to throw in yet another example of how surprising the current behavior can be:

    >>> t1 = datetime.datetime(2002, 10, 27, 1, 30, fold=1, tzinfo=zoneinfo.ZoneInfo(key='US/Eastern'))
    >>> t2 = datetime.datetime(2002, 10, 27, 1, 35, fold=0, tzinfo=zoneinfo.ZoneInfo(key='US/Eastern'))
    >>> t1 < t2
    True
    >>> t1.astimezone(datetime.timezone.utc) < t2.astimezone(datetime.timezone.utc)
    False
    

    t1 and t2 are unambiguously specified to be specific points in time. t1, being after the fold, unarguably happens after t2.

    I feel like most people, not having thoroughly read the documentation and all the past discussions and bug reports on the topic, will expect a timezone-aware datetime to always represent a point in time, including in all math and comparisons between them. After all, that's why they chose to disambiguate with the zoneinfo and fold features given to us. If I wanted timezone-unaware comparisons I would have used a naive datetime.

    This can cause rare bugs when e.g. scheduling code has something scheduled at 1:30am and comparisons within a timezone work as expected every day except one day a year. (Specifically, in my code I want something to happen daily at a specific time in a specific local timezone, and I am explicitly specifying fold=1 to disambiguate DST transitions. So all math is and should be in the local timezone, but I still have to convert to utc for certain comparisons throughout my code)

    All that said, I appreciate the work that's gone into the design and I understand why it's difficult to change anything at this point.

    edit: re-reading the discussion above, I realize that my assertion that "most people will expect point-in-time calculations for timezone-aware arithmetic" is debatable, and that e.g. adding 1 day to a datetime always resulting in the same time on the next day is probably what a lot of people expect. The rationale in this discussion helped me a lot in understanding the "why" of the current behavior. It still remains that my example is pretty surprising no matter how you look at it. I'm not sure what can be done other than add a new datetime-like class that always does all arithmetic and comparisons in utc under the hood.

  18. tusharchou commented on Jul 21, 2025

    @tusharchou

    How can I help ?

  19. NehaJeevan commented on Jul 24, 2025

    @NehaJeevan

    ^I came across this behaviour recently and found this issue. I've updated the docs based on the suggestions from the discussion above.

  20. added a commit that references this issue on Nov 5, 2026
  21. added a commit that references this issue on Nov 28, 2026
  22. Lenormju commented on Nov 28, 2026

    @Lenormju
    Contributor

    I hit this recently, so I searched for related issues and PRs:

    Citing tim-one from this issue:

    IMO, the docs could be made clearer about this. But it's far too late to change the design.

    and about zoneinfo.rst:

    I agree the part you quoted is misleading at best.

    So here is what I suggest:

    1. in datetime.rst, a short section explaining wall time and absolute time semantics, which operations use which, and how to get absolute time semantics within a zone by doing the arithmetic in UTC. The operation notes link to it.
    2. in zoneinfo.rst, replace "handle daylight saving time transitions with no further intervention" with a link to that section.

    One thing I'm not handling here: "same tzinfo" means the same object (is), not the same zone. Two ZoneInfo instances for the same key (after ZoneInfo.clear_cache(), or with ZoneInfo.no_cache()) use absolute time semantics, as jepler showed. That deserves its own change.

    Other issues from users surprised by this behaviour, to show how often it comes up:
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

    docs

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions