diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index a25a698856747..822a9a94bbbd9 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1488,7 +1488,13 @@ def __rsub__(self, other): return (-self) + other # We get here with e.g. datetime objects - return -(self - other) + datetime_result = self - other + if isinstance(datetime_result, DatetimeArray): + raise TypeError( + "TypeError: unsupported operand type(s) for -: " + f"'{type(self).__name__}' and '{type(other).__name__}'" + ) + return -(datetime_result) def __iadd__(self, other) -> Self: result = self + other diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 26dfcf088e74b..c4d189a13f25a 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -15,6 +15,7 @@ import numpy as np import pytest +import re from pandas._libs.tslibs.conversion import localize_pydatetime from pandas._libs.tslibs.offsets import shift_months @@ -1273,8 +1274,10 @@ def test_dt64arr_series_sub_tick_DateOffset(self, box_with_array): result2 = -pd.offsets.Second(5) + ser tm.assert_equal(result2, expected) - msg = "(bad|unsupported) operand type for unary" - with pytest.raises(TypeError, match=msg): + msg = ( + "TypeError: unsupported operand type(s) for -: 'DatetimeArray' and 'Second'" + ) + with pytest.raises(TypeError, match=re.escape(msg)): pd.offsets.Second(5) - ser @pytest.mark.parametrize( @@ -1318,10 +1321,8 @@ def test_dti_add_tick_tzaware(self, tz_aware_fixture, box_with_array): roundtrip = offset - scalar tm.assert_equal(roundtrip, dates) - msg = "|".join( - ["bad operand type for unary -", "cannot subtract DatetimeArray"] - ) - with pytest.raises(TypeError, match=msg): + msg = f"TypeError: unsupported operand type(s) for -: 'DatetimeArray' and '{type(scalar).__name__}'" + with pytest.raises(TypeError, match=re.escape(msg)): scalar - dates # -------------------------------------------------------------