Skip to content

Commit 6385152

Browse files
fix raise of TypeError when subtracting timedelta array
closes #21980
1 parent 716efd3 commit 6385152

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

doc/source/whatsnew/v0.24.0.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ Datetimelike
441441
Timedelta
442442
^^^^^^^^^
443443

444-
-
444+
- Fixed bug where array of timestamp and deltas raised a TypeError: unsupported operand type(s) for -: 'numpy.ndarray' and 'Timedelta' (:issue:`21980`)
445445
-
446446
-
447447

pandas/_libs/tslibs/timedeltas.pyx

+7-3
Original file line numberDiff line numberDiff line change
@@ -542,10 +542,14 @@ def _binary_op_method_timedeltalike(op, name):
542542

543543
elif hasattr(other, 'dtype'):
544544
# nd-array like
545-
if other.dtype.kind not in ['m', 'M']:
545+
if other.dtype.kind not in ['m', 'M', 'O']:
546546
# raise rathering than letting numpy return wrong answer
547547
return NotImplemented
548-
return op(self.to_timedelta64(), other)
548+
try:
549+
converted_other = other.astype('datetime64[ns]')
550+
return op(self.to_timedelta64(), converted_other)
551+
except:
552+
return NotImplemented
549553

550554
elif not _validate_ops_compat(other):
551555
return NotImplemented
@@ -929,7 +933,7 @@ cdef class _Timedelta(timedelta):
929933
def nanoseconds(self):
930934
"""
931935
Return the number of nanoseconds (n), where 0 <= n < 1 microsecond.
932-
936+
933937
Returns
934938
-------
935939
int

pandas/tests/series/test_timeseries.py

+19
Original file line numberDiff line numberDiff line change
@@ -1012,3 +1012,22 @@ def test_get_level_values_box(self):
10121012
index = MultiIndex(levels=levels, labels=labels)
10131013

10141014
assert isinstance(index.get_level_values(0)[0], Timestamp)
1015+
1016+
def test_diff_sub_timedelta(self):
1017+
# GH 21980
1018+
arr = np.array([Timestamp('20130101 9:01'),
1019+
Timestamp('20121230 9:02')])
1020+
exp = np.array([Timestamp('20121231 9:01'),
1021+
Timestamp('20121229 9:02')]).astype('datetime64[ns]')
1022+
res = arr - pd.Timedelta('1D')
1023+
tm.assert_numpy_array_equal(res, exp)
1024+
1025+
def test_diff_sub_timedelta_mixed(self):
1026+
# GH 21980
1027+
now = pd.Timestamp.now()
1028+
arr = np.array([now,
1029+
Timestamp('20121230 9:02')])
1030+
exp = np.array([now - pd.Timedelta('1D'),
1031+
Timestamp('20121229 9:02')]).astype('datetime64[ns]')
1032+
res = arr - pd.Timedelta('1D')
1033+
tm.assert_numpy_array_equal(res, exp)

0 commit comments

Comments
 (0)