diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index b5b3abd01328c..41925139e41ae 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1213,6 +1213,12 @@ class Timedelta(_Timedelta): return other.delta * self return NotImplemented + elif util.is_nan(other): + # i.e. np.nan, but also catch np.float64("NaN") which would + # otherwise get caught by the hasattr(other, "dtype") branch + # incorrectly return a np.timedelta64 object. + return NaT + elif hasattr(other, 'dtype'): # ndarray-like return other * self.to_timedelta64() @@ -1240,6 +1246,12 @@ class Timedelta(_Timedelta): # convert to Timedelta below pass + elif util.is_nan(other): + # i.e. np.nan, but also catch np.float64("NaN") which would + # otherwise get caught by the hasattr(other, "dtype") branch + # incorrectly return a np.timedelta64 object. + return NaT + elif hasattr(other, 'dtype'): return self.to_timedelta64() / other diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index fce1ef29235cc..65709b0eebaf7 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -277,6 +277,14 @@ def test_td_mul_nat(self, op, td_nat): with pytest.raises(TypeError): op(td, td_nat) + @pytest.mark.parametrize('nan', [np.nan, np.float64('NaN'), float('nan')]) + @pytest.mark.parametrize('op', [operator.mul, ops.rmul]) + def test_td_mul_nan(self, op, nan): + # np.float64('NaN') has a 'dtype' attr, avoid treating as array + td = Timedelta(10, unit='d') + result = op(td, nan) + assert result is NaT + @pytest.mark.parametrize('op', [operator.mul, ops.rmul]) def test_td_mul_scalar(self, op): # GH#19738 @@ -328,6 +336,16 @@ def test_td_div_numeric_scalar(self): assert isinstance(result, Timedelta) assert result == Timedelta(days=2) + @pytest.mark.parametrize('nan', [np.nan, np.float64('NaN'), float('nan')]) + def test_td_div_nan(self, nan): + # np.float64('NaN') has a 'dtype' attr, avoid treating as array + td = Timedelta(10, unit='d') + result = td / nan + assert result is NaT + + result = td // nan + assert result is NaT + # --------------------------------------------------------------- # Timedelta.__rdiv__