@@ -195,6 +195,8 @@ def arithmetic_op(left: ArrayLike, right: Any, op):
195
195
196
196
# NB: We assume that extract_array has already been called
197
197
# on `left` and `right`.
198
+ # We need to special-case datetime64/timedelta64 dtypes (e.g. because numpy
199
+ # casts integer dtypes to timedelta64 when operating with timedelta64 - GH#22390)
198
200
lvalues = ensure_wrapped_if_datetimelike (left )
199
201
rvalues = ensure_wrapped_if_datetimelike (right )
200
202
rvalues = _maybe_upcast_for_op (rvalues , lvalues .shape )
@@ -439,11 +441,6 @@ def _maybe_upcast_for_op(obj, shape: Shape):
439
441
Be careful to call this *after* determining the `name` attribute to be
440
442
attached to the result of the arithmetic operation.
441
443
"""
442
- from pandas .core .arrays import (
443
- DatetimeArray ,
444
- TimedeltaArray ,
445
- )
446
-
447
444
if type (obj ) is timedelta :
448
445
# GH#22390 cast up to Timedelta to rely on Timedelta
449
446
# implementation; otherwise operation against numeric-dtype
@@ -453,6 +450,8 @@ def _maybe_upcast_for_op(obj, shape: Shape):
453
450
# GH#28080 numpy casts integer-dtype to datetime64 when doing
454
451
# array[int] + datetime64, which we do not allow
455
452
if isna (obj ):
453
+ from pandas .core .arrays import DatetimeArray
454
+
456
455
# Avoid possible ambiguities with pd.NaT
457
456
obj = obj .astype ("datetime64[ns]" )
458
457
right = np .broadcast_to (obj , shape )
@@ -462,6 +461,8 @@ def _maybe_upcast_for_op(obj, shape: Shape):
462
461
463
462
elif isinstance (obj , np .timedelta64 ):
464
463
if isna (obj ):
464
+ from pandas .core .arrays import TimedeltaArray
465
+
465
466
# wrapping timedelta64("NaT") in Timedelta returns NaT,
466
467
# which would incorrectly be treated as a datetime-NaT, so
467
468
# we broadcast and wrap in a TimedeltaArray
@@ -474,9 +475,4 @@ def _maybe_upcast_for_op(obj, shape: Shape):
474
475
# np.timedelta64(3, 'D') / 2 == np.timedelta64(1, 'D')
475
476
return Timedelta (obj )
476
477
477
- elif isinstance (obj , np .ndarray ) and obj .dtype .kind == "m" :
478
- # GH#22390 Unfortunately we need to special-case right-hand
479
- # timedelta64 dtypes because numpy casts integer dtypes to
480
- # timedelta64 when operating with timedelta64
481
- return TimedeltaArray ._from_sequence (obj )
482
478
return obj
0 commit comments