Skip to content

Commit cb9b7d3

Browse files
committed
BUG: Timedelta.__bool__
Closes pandas-dev#21484
1 parent bf1c3dc commit cb9b7d3

File tree

3 files changed

+18
-0
lines changed

3 files changed

+18
-0
lines changed

doc/source/whatsnew/v0.23.2.txt

+1
Original file line numberDiff line numberDiff line change
@@ -82,4 +82,5 @@ Bug Fixes
8282

8383
**Other**
8484

85+
- Bug in `:class:`Timedelta` where timedeltas shorter than 1 microsecond were considered False (:issue:`21484`)
8586
-

pandas/_libs/tslibs/timedeltas.pyx

+3
Original file line numberDiff line numberDiff line change
@@ -899,6 +899,9 @@ cdef class _Timedelta(timedelta):
899899
def __str__(self):
900900
return self._repr_base(format='long')
901901

902+
def __bool__(self):
903+
return self.value != 0
904+
902905
def isoformat(self):
903906
"""
904907
Format Timedelta as ISO 8601 Duration like

pandas/tests/scalar/timedelta/test_timedelta.py

+14
Original file line numberDiff line numberDiff line change
@@ -588,3 +588,17 @@ def test_components(self):
588588
result = s.dt.components
589589
assert not result.iloc[0].isna().all()
590590
assert result.iloc[1].isna().all()
591+
592+
593+
@pytest.mark.parametrize('value, expected', [
594+
(Timedelta('10S'), True),
595+
(Timedelta('-10S'), True),
596+
(Timedelta(10, unit='ns'), True),
597+
(Timedelta(0, unit='ns'), False),
598+
(Timedelta(-10, unit='ns'), True),
599+
(Timedelta(None), True),
600+
(pd.NaT, True),
601+
])
602+
def test_truthiness(value, expected):
603+
# https://github.com/pandas-dev/pandas/issues/21484
604+
assert bool(value) is expected

0 commit comments

Comments
 (0)