Skip to content

Pure-Python timedelta loses precision with large float arguments #160806

Open

Description

@canblmz1

Bug report

Bug description:

The pure-Python timedelta (Lib/_pydatetime.py) gives a different result than the C one when a large float is passed for weeks, hours, minutes or milliseconds:

>>> import datetime, _pydatetime
>>> datetime.timedelta(weeks=12345678.9)
datetime.timedelta(days=86419752, seconds=25920, microseconds=225)
>>> _pydatetime.timedelta(weeks=12345678.9)
datetime.timedelta(days=86419752, seconds=25919, microseconds=999743)

The C result is the correct one: the float is exactly 12345678.90000000037252902984619140625 weeks, which is 86419752 days, 7:12:00.000225 after rounding. Smaller values are affected too, for example timedelta(weeks=100000.1) is off by 2 µs and timedelta(hours=10000000.1) by 1 µs.

_pydatetime first adds the arguments together with float arithmetic (days += weeks*7, seconds += minutes*60 + hours*3600, microseconds += milliseconds*1000), so the sub-second part is already rounded away before it gets split off. The C version (accum() in _datetimemodule.c) converts the integer part of each argument exactly and only sums the leftover fractional microseconds as a float. That is also what the docs describe ("the fractional microseconds left over from all arguments are combined and their sum is rounded...").

I found this by comparing the two implementations on random inputs. With arguments up to about 1e7, around 1 in 5 results were different, by up to ~2.5 ms.

I'd like to send a PR that makes _pydatetime use the same approach as the C code.

CPython versions tested on:

3.12, 3.13, 3.14, 3.15, CPython main branch

Operating systems tested on:

Windows

Linked PRs

Activity

  1. added
    type-bugAn unexpected behavior, bug, or error
    stdlibStandard Library Python modules in the Lib/ directory
    on Oct 28, 2026
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

    stdlibStandard Library Python modules in the Lib/ directorytype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions