Skip to content

Commit e075e3b

Browse files
mikekutzmaharisbal
authored and
harisbal
committed
BUG: GH19458 fixes precision issue in TimeDelta.total_seconds() (pandas-dev#19783)
1 parent c116584 commit e075e3b

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

doc/source/whatsnew/v0.23.0.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -733,6 +733,7 @@ Datetimelike
733733
- 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`)
734734
- 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`)
735735
- 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`)
736+
- Bug in :func:`Timedelta.total_seconds()` causing precision errors i.e. `Timedelta('30S').total_seconds()==30.000000000000004` (:issue:`19458`)
736737

737738

738739
Timezones

pandas/_libs/tslibs/timedeltas.pyx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -739,7 +739,7 @@ cdef class _Timedelta(timedelta):
739739
"""
740740
Total duration of timedelta in seconds (to ns precision)
741741
"""
742-
return 1e-9 * self.value
742+
return self.value / 1e9
743743

744744
def view(self, dtype):
745745
""" array view compat """

pandas/tests/scalar/timedelta/test_timedelta.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,6 +512,15 @@ def test_implementation_limits(self):
512512
with pytest.raises(OverflowError):
513513
Timedelta(max_td.value + 1, 'ns')
514514

515+
def test_total_seconds_precision(self):
516+
# GH 19458
517+
assert Timedelta('30S').total_seconds() == 30.0
518+
assert Timedelta('0').total_seconds() == 0.0
519+
assert Timedelta('-2S').total_seconds() == -2.0
520+
assert Timedelta('5.324S').total_seconds() == 5.324
521+
assert (Timedelta('30S').total_seconds() - 30.0) < 1e-20
522+
assert (30.0 - Timedelta('30S').total_seconds()) < 1e-20
523+
515524
def test_timedelta_arithmetic(self):
516525
data = pd.Series(['nat', '32 days'], dtype='timedelta64[ns]')
517526
deltas = [timedelta(days=1), Timedelta(1, unit='D')]

0 commit comments

Comments
 (0)