diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index c441244b4415d..b38bc92c6bd86 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -273,7 +273,7 @@ Datetimelike Timedelta ^^^^^^^^^ -- +- Bug with comparisons between :class:`Timedelta` and ``NaT`` raising ``TypeError`` (:issue:`26039`) - - diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 8b71d64db26c6..c1edb664a79a7 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -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__)) diff --git a/pandas/conftest.py b/pandas/conftest.py index 1cb518f426299..8f885c3aae928 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -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): """ diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 43747ea8621d9..0ae4d107d85bd 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -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