Skip to content

Subtracting one datetime from another provides a wrong timedelta if daylight savings change happens between them #96148

Closed as not planned

Description

@wallefan

Bug report

>>> import datetime
>>> import zoneinfo
>>> zone = zoneinfo.ZoneInfo('US/Eastern')
>>> start = datetime.datetime(2022,11,5,23,00,tzinfo=zone)
>>> end = datetime.datetime(2022,11,6,7,00,tzinfo=zone)
>>> end - start
datetime.timedelta(seconds=28800)
>>> end.timestamp() - start.timestamp()
32400.0

Your environment

>>> import sys
>>> sys.version
'3.10.6 (main, Aug  3 2022, 17:39:45) [GCC 12.1.1 20220730]'
>>> sys.platform
 'linux'
  • CPython versions tested on: 3.10.6
  • Operating system and architecture: Arch Linux, x86-64

Activity

  1. added
    type-bug
    on Aug 20, 2022
  2. 0xYasser commented on Aug 21, 2022

    @0xYasser
    Contributor

    The issue is in datetime __sub__ function.

    def __sub__(self, other):

    The early return condition if self._tzinfo is other._tzinfo: should be removed and let utcoffset()check always run to catch this edge case.

  3. tim-one commented on Aug 21, 2022

    @tim-one
    Member

    This is working as designed and as documented:

    3.Subtraction
    ... is defined only if both operands are naive, or if both are aware. If one is aware and the other is naive
    TypeError is raised.
    If both are naive, or both are aware and have the same tzinfo attribute, the tzinfo attributes are ignored, and the result is ...
    If both are aware and have different tzinfo attributes, a-b acts as if a and b were first converted to naive UTC datetimes first ....

    It's generally true that datetime intends that timezone-aware arithmetic be done by converting to UTC first, doing the arithmetic there, and then converting back to the desired timezone. That wasn't the only design decision that was possible, but is the decision that was made, and can't be changed now.

  4. added
    stdlib
    on Nov 26, 2023
  5. StanFromIreland commented on Mar 17, 2025

    @StanFromIreland
    Member

    As Tim mentioned, this is the correct behavior as specified in the docs.

    There is nothing to do here and this should be closed.

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