Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve accuracy of to_pytimedelta #57841

Merged
merged 9 commits into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -313,7 +313,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