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
7 changes: 5 additions & 2 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -779,11 +779,14 @@ 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:
if other is NaT:
return PyObject_RichCompare(other, self, reverse_ops[op])
elif op == Py_EQ:
return False
elif op == Py_NE:
return True
raise TypeError('Cannot compare type {cls} with type {other}'
raise TypeError('Cannot compare type {cls} with '
'type {other}'
.format(cls=type(self).__name__,
other=type(other).__name__))

Expand Down
13 changes: 13 additions & 0 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,19 @@ def all_compare_operators(request):
return request.param


@pytest.fixture(params=['__le__', '__lt__', '__ge__', '__gt__'])
def compare_operators_no_eq_ne(request):
"""
Fixture for dunder names for compare operations except == and !=
* >=
* >
* <
* <=
"""
return request.param


@pytest.fixture(params=[None, 'gzip', 'bz2', 'zip', 'xz'])
def compression(request):
"""
Expand Down
9 changes: 9 additions & 0 deletions pandas/tests/scalar/test_nat.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,3 +348,12 @@ def test_to_numpy_alias():
result = NaT.to_numpy()

assert isna(expected) and isna(result)


@pytest.mark.parametrize("other", [
Timedelta(0), Timestamp(0)
])
def test_nat_comparisons(compare_operators_no_eq_ne, other):
# GH 26039
assert getattr(NaT, compare_operators_no_eq_ne)(other) is False
assert getattr(other, compare_operators_no_eq_ne)(NaT) is False