Skip to content

Commit 1cd7ae6

Browse files
jbrockmendelWillAyd
authored andcommitted
BUG: datetime64 - Timestamp incorrectly raising TypeError (#28286)
1 parent 7111927 commit 1cd7ae6

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

doc/source/whatsnew/v1.0.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ Datetimelike
9898
- Bug in :meth:`Series.dt` property lookups when the underlying data is read-only (:issue:`27529`)
9999
- Bug in ``HDFStore.__getitem__`` incorrectly reading tz attribute created in Python 2 (:issue:`26443`)
100100
- Bug in :meth:`pandas.core.groupby.SeriesGroupBy.nunique` where ``NaT`` values were interfering with the count of unique values (:issue:`27951`)
101+
- Bug in :class:`Timestamp` subtraction when subtracting a :class:`Timestamp` from a ``np.datetime64`` object incorrectly raising ``TypeError`` (:issue:`28286`)
102+
-
101103

102104

103105
Timedelta

pandas/_libs/tslibs/c_timestamp.pyx

+5
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,11 @@ cdef class _Timestamp(datetime):
312312
except (OverflowError, OutOfBoundsDatetime):
313313
pass
314314

315+
elif is_datetime64_object(self):
316+
# GH#28286 cython semantics for __rsub__, `other` is actually
317+
# the Timestamp
318+
return type(other)(self) - other
319+
315320
# scalar Timestamp/datetime - Timedelta -> yields a Timestamp (with
316321
# same timezone if specified)
317322
return datetime.__sub__(self, other)

pandas/tests/scalar/timestamp/test_arithmetic.py

+14
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,20 @@ def test_delta_preserve_nanos(self):
6666
result = val + timedelta(1)
6767
assert result.nanosecond == val.nanosecond
6868

69+
def test_rsub_dtscalars(self, tz_naive_fixture):
70+
# In particular, check that datetime64 - Timestamp works GH#28286
71+
td = Timedelta(1235345642000)
72+
ts = Timestamp.now(tz_naive_fixture)
73+
other = ts + td
74+
75+
assert other - ts == td
76+
assert other.to_pydatetime() - ts == td
77+
if tz_naive_fixture is None:
78+
assert other.to_datetime64() - ts == td
79+
else:
80+
with pytest.raises(TypeError, match="subtraction must have"):
81+
other.to_datetime64() - ts
82+
6983
def test_timestamp_sub_datetime(self):
7084
dt = datetime(2013, 10, 12)
7185
ts = Timestamp(datetime(2013, 10, 13))

0 commit comments

Comments
 (0)