@@ -195,6 +195,8 @@ def arithmetic_op(left: ArrayLike, right: Any, op):
195195
196196 # NB: We assume that extract_array has already been called
197197 # 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)
198200 lvalues = ensure_wrapped_if_datetimelike (left )
199201 rvalues = ensure_wrapped_if_datetimelike (right )
200202 rvalues = _maybe_upcast_for_op (rvalues , lvalues .shape )
@@ -439,11 +441,6 @@ def _maybe_upcast_for_op(obj, shape: Shape):
439441 Be careful to call this *after* determining the `name` attribute to be
440442 attached to the result of the arithmetic operation.
441443 """
442- from pandas .core .arrays import (
443- DatetimeArray ,
444- TimedeltaArray ,
445- )
446-
447444 if type (obj ) is timedelta :
448445 # GH#22390 cast up to Timedelta to rely on Timedelta
449446 # implementation; otherwise operation against numeric-dtype
@@ -453,6 +450,8 @@ def _maybe_upcast_for_op(obj, shape: Shape):
453450 # GH#28080 numpy casts integer-dtype to datetime64 when doing
454451 # array[int] + datetime64, which we do not allow
455452 if isna (obj ):
453+ from pandas .core .arrays import DatetimeArray
454+
456455 # Avoid possible ambiguities with pd.NaT
457456 obj = obj .astype ("datetime64[ns]" )
458457 right = np .broadcast_to (obj , shape )
@@ -462,6 +461,8 @@ def _maybe_upcast_for_op(obj, shape: Shape):
462461
463462 elif isinstance (obj , np .timedelta64 ):
464463 if isna (obj ):
464+ from pandas .core .arrays import TimedeltaArray
465+
465466 # wrapping timedelta64("NaT") in Timedelta returns NaT,
466467 # which would incorrectly be treated as a datetime-NaT, so
467468 # we broadcast and wrap in a TimedeltaArray
@@ -474,9 +475,4 @@ def _maybe_upcast_for_op(obj, shape: Shape):
474475 # np.timedelta64(3, 'D') / 2 == np.timedelta64(1, 'D')
475476 return Timedelta (obj )
476477
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 )
482478 return obj
0 commit comments