python / python/cpython

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

Open
#146,236 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

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
  • gh-146294

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the documented datetime comparison and subtraction behavior with the America/Los_Angeles zoneinfo examples and inspect the datetime.datetime ordering and subtraction entry points. Compare the results with timestamp ordering and the stated documentation semantics; done means the behavior and documentation agree across the DST fold case, with relevant regression coverage.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.