diff --git a/pandas/_libs/tslibs/c_timestamp.pyx b/pandas/_libs/tslibs/c_timestamp.pyx index 2c72cec18f096..96dd54e38204a 100644 --- a/pandas/_libs/tslibs/c_timestamp.pyx +++ b/pandas/_libs/tslibs/c_timestamp.pyx @@ -119,6 +119,10 @@ cdef class _Timestamp(datetime): else: return NotImplemented + + if op in [Py_EQ, Py_NE]: + return op == Py_NE + self._assert_tzawareness_compat(other) return cmp_scalar(self.value, ots.value, op) @@ -179,8 +183,7 @@ cdef class _Timestamp(datetime): cdef _assert_tzawareness_compat(_Timestamp self, datetime other): if self.tzinfo is None: if other.tzinfo is not None: - raise TypeError('Cannot compare tz-naive and tz-aware ' - 'timestamps') + raise TypeError("Cannot compare tz-naive and tz-aware timestamps") elif other.tzinfo is None: raise TypeError('Cannot compare tz-naive and tz-aware timestamps') diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index d3f9ac4f3f8b2..317745f318372 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -526,7 +526,7 @@ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): @pytest.mark.parametrize( "op", - [operator.eq, operator.ne, operator.gt, operator.ge, operator.lt, operator.le], + [operator.gt, operator.ge, operator.lt, operator.le], ) def test_comparison_tzawareness_compat(self, op, box_df_fail): # GH#18162 diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index fce4fa6eb1eaa..8a58c17ded1a2 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -85,10 +85,6 @@ def test_cant_compare_tz_naive_w_aware(self, utc_fixture): a = Timestamp("3/12/2012") b = Timestamp("3/12/2012", tz=utc_fixture) - with pytest.raises(TypeError): - a == b - with pytest.raises(TypeError): - a != b with pytest.raises(TypeError): a < b with pytest.raises(TypeError): @@ -98,10 +94,6 @@ def test_cant_compare_tz_naive_w_aware(self, utc_fixture): with pytest.raises(TypeError): a >= b - with pytest.raises(TypeError): - b == a - with pytest.raises(TypeError): - b != a with pytest.raises(TypeError): b < a with pytest.raises(TypeError): @@ -161,6 +153,20 @@ def test_compare_zerodim_array(self): result = arr > ts assert result is False + def test_timestamp_compare_tz(self): + # https://github.com/pandas-dev/pandas/issues/28507 + ts = Timestamp.now() + ts2 = ts.tz_localize("UTC") + + dt = ts.to_pydatetime() + dt2 = ts2.to_pydatetime() + + assert ts != ts2 + assert dt != dt2 + + assert not ts == ts2 + assert not dt == dt2 + def test_rich_comparison_with_unsupported_type(): # Comparisons with unsupported objects should return NotImplemented