You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Pure-Python timedelta loses precision with large float arguments #160806
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:
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.
Activity