Skip to content

Commit

Permalink
improve accuracy of to_pytimedelta (pandas-dev#57841)
Browse files Browse the repository at this point in the history
* improve accuracy of to_pytimedelta

* f

* f

* whatsnew

* f

---------

Co-authored-by: Rohan Jain <[email protected]>
  • Loading branch information
2 people authored and pmhatre1 committed May 7, 2024
1 parent 89043a6 commit 8fe650c
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ Datetimelike

Timedelta
^^^^^^^^^
-
- Accuracy improvement in :meth:`Timedelta.to_pytimedelta` to round microseconds consistently for large nanosecond based Timedelta (:issue:`57841`)
-

Timezones
Expand Down
5 changes: 4 additions & 1 deletion pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1376,7 +1376,10 @@ cdef class _Timedelta(timedelta):
datetime.timedelta(days=3)
"""
if self._creso == NPY_FR_ns:
return timedelta(microseconds=int(self._value) / 1000)
us, remainder = divmod(self._value, 1000)
if remainder >= 500:
us += 1
return timedelta(microseconds=us)

# TODO(@WillAyd): is this the right way to use components?
self._ensure_components()
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/scalar/timedelta/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -665,3 +665,10 @@ def test_timedelta_attribute_precision():
result += td.nanoseconds
expected = td._value
assert result == expected


def test_to_pytimedelta_large_values():
td = Timedelta(1152921504609987375, unit="ns")
result = td.to_pytimedelta()
expected = timedelta(days=13343, seconds=86304, microseconds=609987)
assert result == expected

0 comments on commit 8fe650c

Please sign in to comment.