diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1ac6d075946dd..52503f06c7e5c 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -443,7 +443,7 @@ Datetimelike Timedelta ^^^^^^^^^ -- +- Bug in :class:`DataFrame` with ``dtype='datetime64[ns]'`` when adding :class:`Timedelta` (:issue:`22005`) - - diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ffa2267dd6877..a461d963f253a 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2713,6 +2713,11 @@ def _try_coerce_args(self, values, other): "naive Block") other_mask = isna(other) other = other.asm8.view('i8') + elif isinstance(other, (timedelta, np.timedelta64)): + if not isinstance(other, Timedelta): + other = Timedelta(other) + other_mask = isna(other) + other = other.asm8.view('i8') elif hasattr(other, 'dtype') and is_datetime64_dtype(other): other_mask = isna(other) other = other.astype('i8', copy=False).view('i8') diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index fb381a5640519..60951b30ffa10 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import datetime + import pytest import numpy as np @@ -211,6 +213,23 @@ def test_df_sub_datetime64_not_ns(self): pd.Timedelta(days=2)]) tm.assert_frame_equal(res, expected) + @pytest.mark.parametrize('other', [ + pd.Timedelta('1d'), + datetime.timedelta(days=1), + np.timedelta64(1, 'D') + ]) + def test_timestamp_df_add_timedelta(self, other): + # GH 22005 + expected = pd.DataFrame([pd.Timestamp('2018-01-02')]) + result = pd.DataFrame([pd.Timestamp('2018-01-01')]) + other + tm.assert_frame_equal(result, expected) + + result = pd.DataFrame([pd.Timestamp('2018-01-03')]) - other + tm.assert_frame_equal(result, expected) + + result = other + pd.DataFrame([pd.Timestamp('2018-01-01')]) + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize('data', [ [1, 2, 3], [1.1, 2.2, 3.3],