diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index a593a03de5c25..43756082a7442 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -543,7 +543,7 @@ Datetimelike Timedelta ^^^^^^^^^ - Bug in division of all-``NaT`` :class:`TimeDeltaIndex`, :class:`Series` or :class:`DataFrame` column with object-dtype arraylike of numbers failing to infer the result as timedelta64-dtype (:issue:`39750`) -- +- Bug in floor division of ``timedelta64[ns]`` data with a scalar returning garbage values (:issue:`44466`) Timezones ^^^^^^^^^ diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 3d8f9f7edcc74..91e90ebdb6253 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -651,8 +651,7 @@ def __floordiv__(self, other): # at this point we should only have numeric scalars; anything # else will raise - result = self.asi8 // other - np.putmask(result, self._isnan, iNaT) + result = self._ndarray / other freq = None if self.freq is not None: # Note: freq gets division, not floor-division @@ -661,7 +660,7 @@ def __floordiv__(self, other): # e.g. if self.freq is Nano(1) then dividing by 2 # rounds down to zero freq = None - return type(self)(result.view("m8[ns]"), freq=freq) + return type(self)(result, freq=freq) if not hasattr(other, "dtype"): # list, tuple diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 8078e8c90a2bf..93332b9b96f84 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -1981,6 +1981,20 @@ def test_td64arr_div_numeric_scalar(self, box_with_array, two): with pytest.raises(TypeError, match="Cannot divide"): two / tdser + @pytest.mark.parametrize("two", [2, 2.0, np.array(2), np.array(2.0)]) + def test_td64arr_floordiv_numeric_scalar(self, box_with_array, two): + tdser = Series(["59 Days", "59 Days", "NaT"], dtype="m8[ns]") + expected = Series(["29.5D", "29.5D", "NaT"], dtype="timedelta64[ns]") + + tdser = tm.box_expected(tdser, box_with_array) + expected = tm.box_expected(expected, box_with_array) + + result = tdser // two + tm.assert_equal(result, expected) + + with pytest.raises(TypeError, match="Cannot divide"): + two // tdser + @pytest.mark.parametrize( "vector", [np.array([20, 30, 40]), pd.Index([20, 30, 40]), Series([20, 30, 40])],