Skip to content

BUG: GH19458 fixes precision issue in TimeDelta.total_seconds() #19783

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

Merged
merged 4 commits into from
Feb 20, 2018
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
1 change: 1 addition & 0 deletions doc/source/whatsnew/v0.23.0.txt
Original file line number Diff line number Diff line change
Expand Up @@ -733,6 +733,7 @@ Datetimelike
- Bug in :func:`to_datetime` where passing an out-of-bounds datetime with ``errors='coerce'`` and ``utc=True`` would raise ``OutOfBoundsDatetime`` instead of parsing to ``NaT`` (:issue:`19612`)
- Bug in :func:`Timedelta.__add__`, :func:`Timedelta.__sub__` where adding or subtracting a ``np.timedelta64`` object would return another ``np.timedelta64`` instead of a ``Timedelta`` (:issue:`19738`)
- Bug in :func:`Timedelta.__floordiv__`, :func:`Timedelta.__rfloordiv__` where operating with a ``Tick`` object would raise a ``TypeError`` instead of returning a numeric value (:issue:`19738`)
- Bug in :func:`Timedelta.total_seconds()` causing precision errors i.e. `Timedelta('30S').total_seconds()==30.000000000000004` (:issue:`19458`)


Timezones
Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -739,7 +739,7 @@ cdef class _Timedelta(timedelta):
"""
Total duration of timedelta in seconds (to ns precision)
"""
return 1e-9 * self.value
return self.value / 1e9

def view(self, dtype):
""" array view compat """
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/scalar/timedelta/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,6 +512,15 @@ def test_implementation_limits(self):
with pytest.raises(OverflowError):
Timedelta(max_td.value + 1, 'ns')

def test_total_seconds_precision(self):
# GH 19458
assert Timedelta('30S').total_seconds() == 30.0
assert Timedelta('0').total_seconds() == 0.0
assert Timedelta('-2S').total_seconds() == -2.0
assert Timedelta('5.324S').total_seconds() == 5.324
assert (Timedelta('30S').total_seconds() - 30.0) < 1e-20
assert (30.0 - Timedelta('30S').total_seconds()) < 1e-20

def test_timedelta_arithmetic(self):
data = pd.Series(['nat', '32 days'], dtype='timedelta64[ns]')
deltas = [timedelta(days=1), Timedelta(1, unit='D')]
Expand Down