Skip to content

Commit cf40e56

Browse files
rohanjain101Rohan Jain
and
Rohan Jain
authored
improve accuracy of to_pytimedelta (#57841)
* improve accuracy of to_pytimedelta * f * f * whatsnew * f --------- Co-authored-by: Rohan Jain <[email protected]>
1 parent 63cad6b commit cf40e56

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

doc/source/whatsnew/v3.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -319,7 +319,7 @@ Datetimelike
319319

320320
Timedelta
321321
^^^^^^^^^
322-
-
322+
- Accuracy improvement in :meth:`Timedelta.to_pytimedelta` to round microseconds consistently for large nanosecond based Timedelta (:issue:`57841`)
323323
-
324324

325325
Timezones

pandas/_libs/tslibs/timedeltas.pyx

+4-1
Original file line numberDiff line numberDiff line change
@@ -1376,7 +1376,10 @@ cdef class _Timedelta(timedelta):
13761376
datetime.timedelta(days=3)
13771377
"""
13781378
if self._creso == NPY_FR_ns:
1379-
return timedelta(microseconds=int(self._value) / 1000)
1379+
us, remainder = divmod(self._value, 1000)
1380+
if remainder >= 500:
1381+
us += 1
1382+
return timedelta(microseconds=us)
13801383

13811384
# TODO(@WillAyd): is this the right way to use components?
13821385
self._ensure_components()

pandas/tests/scalar/timedelta/test_timedelta.py

+7
Original file line numberDiff line numberDiff line change
@@ -665,3 +665,10 @@ def test_timedelta_attribute_precision():
665665
result += td.nanoseconds
666666
expected = td._value
667667
assert result == expected
668+
669+
670+
def test_to_pytimedelta_large_values():
671+
td = Timedelta(1152921504609987375, unit="ns")
672+
result = td.to_pytimedelta()
673+
expected = timedelta(days=13343, seconds=86304, microseconds=609987)
674+
assert result == expected

0 commit comments

Comments
 (0)