Skip to content

Commit e1736f9

Browse files
TomAugspurgerjorisvandenbossche
authored andcommitted
BUG: Timedelta.__bool__ (#21485)
Closes #21484 (cherry picked from commit d5a1232)
1 parent f8dbd88 commit e1736f9

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

doc/source/whatsnew/v0.23.2.txt

+6-3
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,13 @@ Bug Fixes
4343
-
4444
-
4545

46-
**Conversion**
46+
**Timedelta**
4747

48+
- Bug in :class:`Timedelta` where non-zero timedeltas shorter than 1 microsecond were considered False (:issue:`21484`)
4849

49-
-
50+
**Conversion**
51+
52+
- Bug in :meth:`Series.nlargest` for signed and unsigned integer dtypes when the minimum value is present (:issue:`21426`)
5053
-
5154

5255
**Indexing**
@@ -75,10 +78,10 @@ Bug Fixes
7578
-
7679

7780
**Timezones**
81+
7882
- Bug in :class:`Timestamp` and :class:`DatetimeIndex` where passing a :class:`Timestamp` localized after a DST transition would return a datetime before the DST transition (:issue:`20854`)
7983
- Bug in comparing :class:`DataFrame`s with tz-aware :class:`DatetimeIndex` columns with a DST transition that raised a ``KeyError`` (:issue:`19970`)
8084

8185
**Other**
8286

83-
- Bug in :meth:`Series.nlargest` for signed and unsigned integer dtypes when the minimum value is present (:issue:`21426`)
8487
-

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)