Skip to content

Commit 187630b

Browse files
ArtificialQualiajreback
authored andcommitted
BUG: Fix NaT comparisons with Timedelta (#26039) (#26046)
1 parent 310a7e3 commit 187630b

File tree

4 files changed

+28
-3
lines changed

4 files changed

+28
-3
lines changed

doc/source/whatsnew/v0.25.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -275,7 +275,7 @@ Datetimelike
275275
Timedelta
276276
^^^^^^^^^
277277

278-
-
278+
- Bug with comparisons between :class:`Timedelta` and ``NaT`` raising ``TypeError`` (:issue:`26039`)
279279
-
280280
-
281281

pandas/_libs/tslibs/timedeltas.pyx

+5-2
Original file line numberDiff line numberDiff line change
@@ -776,11 +776,14 @@ cdef class _Timedelta(timedelta):
776776
return PyObject_RichCompare(np.array([self]), other, op)
777777
return PyObject_RichCompare(other, self, reverse_ops[op])
778778
else:
779-
if op == Py_EQ:
779+
if other is NaT:
780+
return PyObject_RichCompare(other, self, reverse_ops[op])
781+
elif op == Py_EQ:
780782
return False
781783
elif op == Py_NE:
782784
return True
783-
raise TypeError('Cannot compare type {cls} with type {other}'
785+
raise TypeError('Cannot compare type {cls} with '
786+
'type {other}'
784787
.format(cls=type(self).__name__,
785788
other=type(other).__name__))
786789

pandas/conftest.py

+13
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,19 @@ def all_compare_operators(request):
221221
return request.param
222222

223223

224+
@pytest.fixture(params=['__le__', '__lt__', '__ge__', '__gt__'])
225+
def compare_operators_no_eq_ne(request):
226+
"""
227+
Fixture for dunder names for compare operations except == and !=
228+
229+
* >=
230+
* >
231+
* <
232+
* <=
233+
"""
234+
return request.param
235+
236+
224237
@pytest.fixture(params=[None, 'gzip', 'bz2', 'zip', 'xz'])
225238
def compression(request):
226239
"""

pandas/tests/scalar/test_nat.py

+9
Original file line numberDiff line numberDiff line change
@@ -348,3 +348,12 @@ def test_to_numpy_alias():
348348
result = NaT.to_numpy()
349349

350350
assert isna(expected) and isna(result)
351+
352+
353+
@pytest.mark.parametrize("other", [
354+
Timedelta(0), Timestamp(0)
355+
])
356+
def test_nat_comparisons(compare_operators_no_eq_ne, other):
357+
# GH 26039
358+
assert getattr(NaT, compare_operators_no_eq_ne)(other) is False
359+
assert getattr(other, compare_operators_no_eq_ne)(NaT) is False

0 commit comments

Comments
 (0)