Skip to content

Commit b7e786e

Browse files
authored
BUG: Timestamp cmp ndarray[dt64] (#33346)
1 parent ec0e284 commit b7e786e

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

pandas/_libs/tslibs/c_timestamp.pyx

+12
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,18 @@ cdef class _Timestamp(datetime):
114114
return NotImplemented
115115
elif is_array(other):
116116
# avoid recursion error GH#15183
117+
if other.dtype.kind == "M":
118+
if self.tz is None:
119+
return PyObject_RichCompare(self.asm8, other, op)
120+
raise TypeError(
121+
"Cannot compare tz-naive and tz-aware timestamps"
122+
)
123+
if other.dtype.kind == "O":
124+
# Operate element-wise
125+
return np.array(
126+
[PyObject_RichCompare(self, x, op) for x in other],
127+
dtype=bool,
128+
)
117129
return PyObject_RichCompare(np.array([self]), other, op)
118130
return PyObject_RichCompare(other, self, reverse_ops[op])
119131
else:

pandas/tests/scalar/timestamp/test_comparisons.py

+52
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,61 @@
55
import pytest
66

77
from pandas import Timestamp
8+
import pandas._testing as tm
89

910

1011
class TestTimestampComparison:
12+
def test_comparison_dt64_ndarray(self):
13+
ts = Timestamp.now()
14+
ts2 = Timestamp("2019-04-05")
15+
arr = np.array([[ts.asm8, ts2.asm8]], dtype="M8[ns]")
16+
17+
result = ts == arr
18+
expected = np.array([[True, False]], dtype=bool)
19+
tm.assert_numpy_array_equal(result, expected)
20+
21+
result = arr == ts
22+
tm.assert_numpy_array_equal(result, expected)
23+
24+
result = ts != arr
25+
tm.assert_numpy_array_equal(result, ~expected)
26+
27+
result = arr != ts
28+
tm.assert_numpy_array_equal(result, ~expected)
29+
30+
result = ts2 < arr
31+
tm.assert_numpy_array_equal(result, expected)
32+
33+
result = arr < ts2
34+
tm.assert_numpy_array_equal(result, np.array([[False, False]], dtype=bool))
35+
36+
result = ts2 <= arr
37+
tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool))
38+
39+
result = arr <= ts2
40+
tm.assert_numpy_array_equal(result, ~expected)
41+
42+
result = ts >= arr
43+
tm.assert_numpy_array_equal(result, np.array([[True, True]], dtype=bool))
44+
45+
result = arr >= ts
46+
tm.assert_numpy_array_equal(result, np.array([[True, False]], dtype=bool))
47+
48+
@pytest.mark.parametrize("reverse", [True, False])
49+
def test_comparison_dt64_ndarray_tzaware(self, reverse, all_compare_operators):
50+
op = getattr(operator, all_compare_operators.strip("__"))
51+
52+
ts = Timestamp.now("UTC")
53+
arr = np.array([ts.asm8, ts.asm8], dtype="M8[ns]")
54+
55+
left, right = ts, arr
56+
if reverse:
57+
left, right = arr, ts
58+
59+
msg = "Cannot compare tz-naive and tz-aware timestamps"
60+
with pytest.raises(TypeError, match=msg):
61+
op(left, right)
62+
1163
def test_comparison_object_array(self):
1264
# GH#15183
1365
ts = Timestamp("2011-01-03 00:00:00-0500", tz="US/Eastern")

0 commit comments

Comments
 (0)