Skip to content

datetime: Comparision and subtraction of datetime objects does not account for DST changes #146236

Open

Description

@jepler

Bug report

Bug description:

The documentation of datetime ordering predicates says both that "datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time, taking into account the time zone" but also "If both comparands are aware, and have the same tzinfo attribute, the tzinfo and fold attributes are ignored"

I believe that ignoring fold, though documented, is incorrect, and contradicts the earlier "precedes ... in time" explanation of what the expression dt1 < dt2 means. If avoiding a conversion to UTC is an important performance optimization, a possibility is to continue to avoid it provided that the fold= and tzinfo= values are the same in both comparands.

>>> from datetime import datetime
>>> import zoneinfo
>>> la = zoneinfo.ZoneInfo("America/Los_Angeles")
>>> t1 = datetime.fromtimestamp(1604221200.0, tz=la)
>>> t2 = datetime.fromtimestamp(1604217660.0, tz=la)
>>> t1 < t2
True
>>> t1.timestamp() < t2.timestamp()
False

Tested on: 3.13.5, 3.15.0a2

CPython versions tested on:

3.15

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Mar 21, 2026
  2. added
    stdlib
    on Mar 21, 2026
  3. jepler commented on Mar 21, 2026

    @jepler
    ContributorAuthor

    A difficulty is that datetime.time objects ALSO have a fold= attribute. However, as time objects are not associated with a particular moment in time, they cannot be disambiguated by conversion to an unambiguous timestamp. Thus, the suggested logic for comparing datetimes with differing fold attributes cannot be extended to comparing times.

    It's tempting to suggest using a simple rule like "the duration of a fold is exactly one hour", but this is not necessarily true. For instance, according to Wikipedia, Lord Howe Island currently applies a 30 minute shift during the summer months.

  4. jepler commented on Mar 23, 2026

    @jepler
    ContributorAuthor

    The comparison operations of datetime objects also are not accounting for DST changes in the way I expect.

    from datetime import datetime, UTC, timedelta
    
    t1_utc = datetime.fromtimestamp(1604217660.0, tz=UTC)
    t2_utc = t1_utc + timedelta(minutes=59)
    
    print("in UTC")
    print(f"{t1_utc!r} {t2_utc=!r}")
    print("t1 is before t2?", t1_utc < t2_utc)
    print("duration t1->t2", t2_utc - t1_utc)
    print()
    
    import zoneinfo
    la = zoneinfo.ZoneInfo("America/Los_Angeles")
    t1_la = t1_utc.astimezone(la)
    t2_la = t2_utc.astimezone(la)
    
    print("in America/Los Angeles")
    print(f"{t1_la!r} {t2_la=!r}")
    print("t1 is before t2?", t1_la < t2_la)
    print("duration t1->t2", t2_la - t1_la)
    print()

    Output (in any python up to 3.15.0a2):

    in UTC
    datetime.datetime(2020, 11, 1, 8, 1, tzinfo=datetime.timezone.utc) t2_utc=datetime.datetime(2020, 11, 1, 9, 0, tzinfo=datetime.timezone.utc)
    t1 is before t2? True
    duration t1->t2 0:59:00
    
    in America/Los Angeles
    datetime.datetime(2020, 11, 1, 1, 1, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles')) t2_la=datetime.datetime(2020, 11, 1, 1, 0, fold=1, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles'))
    t1 is before t2? False
    duration t1->t2 -1 day, 23:59:00
    

    My expectation is that the result of these operations (subtraction and comparison) on datetimes should be the same regardless of what timezone they are converted into.

  5. changed the title [-]datetime: Comparision does not correctly account for `fold`ed time[/-] [+]datetime: Comparision and subtraction of datetime objects does not account for DST changes[/+] on Mar 23, 2026
  6. jepler commented on Mar 24, 2026

    @jepler
    ContributorAuthor
              # What happens in the fall-back fold?
              u = datetime(2002, 10, 27, 5, 30, tzinfo=Eastern2) 
              t0 = Eastern2.fromutc(u)
              u += HOUR
              t1 = Eastern2.fromutc(u)
              self.assertEqual(t0, t1)
              self.assertEqual(t0.fold, 0)
              self.assertEqual(t1.fold, 1)

    The current behavior, that the two instants during a fold are equal, is explicitly tested.

          def test_aware_subtract(self):
              cls = self.theclass
      
              # Ensure that utcoffset() is ignored when the operands have the
              # same tzinfo member.

    The current behavior, that subtracting timestamps with identical timezones ignores changes in DST, is explicitly tested.

    Besides that, changing the implementation of _pydatetime.datetime._cmp so that it calls self.utcoffset() for operands with is-identical tzinfo causes a RecursionError in test.datetimetester.TestLocalTimeDisambiguation_Fast.test_vilnius_1941_fromutc, since that utcoffset implementation depends in turn on comparing objects with identical non-None tzinfo values.

    This leaves me thinking that the current implementation needs to be better documented. Minimally, stating that for aware objects, equality and ordering can DIFFER from the result if you utc-convert the dates, and possibly explicitly suggesting that depending on the needed semantics, it may be desirable to utc-convert the dates.

  7. jepler commented on Mar 24, 2026

    @jepler
    ContributorAuthor
    >>> from zoneinfo import ZoneInfo
    >>> la1 = ZoneInfo("America/Los_Angeles")
    >>> la2 = ZoneInfo("America/Los_Angeles")
    >>> la1 is la2
    True
    >>> ZoneInfo.clear_cache()
    >>> la2 = ZoneInfo("America/Los_Angeles")
    >>> la1 is la2
    False
    >>> t1 = datetime.fromtimestamp(1604221200.0, tz=la1)
    >>> t2 = datetime.fromtimestamp(1604217660.0, tz=la2)
    >>> t1 < t2
    False
    

    The dependence on object identity here is unfortunate, because it doesn't capture "time zone identity". The result of subtracting two aware datetime instances is different when the time zone objects are not object identical but implement the same DST rule. The result of the comparison here differs from the one in the initial issue description, simply because the two copies of the Pacific Time timezone object are distinct.

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

    stdlibtype-bug

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions