Skip to content

BUG: Fix NaT comparisons with Timedelta (#26039) #26046

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 11 commits into from
Apr 28, 2019
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v0.25.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ Datetimelike
Timedelta
^^^^^^^^^

-
- Bug with comparisons between :class:`Timedelta` and ``NaT`` raising ``TypeError`` (:issue:`26039`)
-
-

Expand Down
18 changes: 11 additions & 7 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -779,13 +779,17 @@ cdef class _Timedelta(timedelta):
return PyObject_RichCompare(np.array([self]), other, op)
return PyObject_RichCompare(other, self, reverse_ops[op])
else:
if op == Py_EQ:
return False
elif op == Py_NE:
return True
raise TypeError('Cannot compare type {cls} with type {other}'
.format(cls=type(self).__name__,
other=type(other).__name__))
if other is NaT:
return PyObject_RichCompare(other, self, reverse_ops[op])
else:
if op == Py_EQ:
return False
elif op == Py_NE:
return True
raise TypeError('Cannot compare type {cls} with '
'type {other}'
.format(cls=type(self).__name__,
other=type(other).__name__))

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

Expand Down
34 changes: 34 additions & 0 deletions pandas/tests/scalar/timedelta/test_arithmetic.py
Original file line number Diff line number Diff line change
Expand Up @@ -689,3 +689,37 @@ def test_rdivmod_invalid(self):
def test_td_op_timedelta_timedeltalike_array(self, op, arr):
with pytest.raises(TypeError):
op(arr, Timedelta('1D'))


class TestTimedeltaCompare():
"""
Tests for Timedelta comparisons.
"""

def test_timedelta_nat_comparisons(self):
# GH 26039
td = pd.Timedelta(0)

result = td > NaT
assert result is False

result = td >= NaT
assert result is False

result = td < NaT
assert result is False

result = td <= NaT
assert result is False

result = NaT > td
assert result is False

result = NaT >= td
assert result is False

result = NaT < td
assert result is False

result = NaT <= td
assert result is False