Skip to content

Commit 155a549

Browse files
BUG: Fix NaT comparisons with Timedelta (pandas-dev#26039)
1 parent 6d9b702 commit 155a549

File tree

3 files changed

+39
-8
lines changed

3 files changed

+39
-8
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,7 @@ Datetimelike
273273
Timedelta
274274
^^^^^^^^^
275275

276-
-
276+
- Bug with comparisons between :class:`Timedelta` and ``NaT`` raising ``TypeError`` (:issue:`26039`)
277277
-
278278
-
279279

pandas/_libs/tslibs/timedeltas.pyx

+10-7
Original file line numberDiff line numberDiff line change
@@ -779,13 +779,16 @@ cdef class _Timedelta(timedelta):
779779
return PyObject_RichCompare(np.array([self]), other, op)
780780
return PyObject_RichCompare(other, self, reverse_ops[op])
781781
else:
782-
if op == Py_EQ:
783-
return False
784-
elif op == Py_NE:
785-
return True
786-
raise TypeError('Cannot compare type {cls} with type {other}'
787-
.format(cls=type(self).__name__,
788-
other=type(other).__name__))
782+
if other is NaT:
783+
return PyObject_RichCompare(other, self, reverse_ops[op])
784+
else:
785+
if op == Py_EQ:
786+
return False
787+
elif op == Py_NE:
788+
return True
789+
raise TypeError('Cannot compare type {cls} with type {other}'
790+
.format(cls=type(self).__name__,
791+
other=type(other).__name__))
789792

790793
return cmp_scalar(self.value, ots.value, op)
791794

pandas/tests/arithmetic/test_timedelta64.py

+28
Original file line numberDiff line numberDiff line change
@@ -441,6 +441,34 @@ def test_timedelta(self, freq):
441441
tm.assert_index_equal(result1, result4)
442442
tm.assert_index_equal(result2, result3)
443443

444+
def test_timedelta_nat_comparisons(self):
445+
# GH 26039
446+
td = pd.Timedelta(0)
447+
448+
result = td > NaT
449+
assert result == False
450+
451+
result = td >= NaT
452+
assert result == False
453+
454+
result = td < NaT
455+
assert result == False
456+
457+
result = td <= NaT
458+
assert result == False
459+
460+
result = NaT > td
461+
assert result == False
462+
463+
result = NaT >= td
464+
assert result == False
465+
466+
result = NaT < td
467+
assert result == False
468+
469+
result = NaT <= td
470+
assert result == False
471+
444472

445473
class TestAddSubNaTMasking(object):
446474
# TODO: parametrize over boxes

0 commit comments

Comments
 (0)