diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 8fe3023e9537cd..9ffe68e68e90e7 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -440,7 +440,7 @@ Datetimelike Timedelta ^^^^^^^^^ -- +- Bug in :class:`DataFrame` with ``dtype='datetime64[ns]'`` when adding :class:`Timedelta` (:issue:`22007`) - - diff --git a/pandas/core/internals.py b/pandas/core/internals.py index 5a87a8368dc88c..51e9882c51d02d 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -2724,6 +2724,11 @@ def _try_coerce_args(self, values, other): "naive Block") other_mask = isna(other) other = other.asm8.view('i8') + elif isinstance(other, (Timedelta, timedelta, np.timedelta64)): + # should be the same as TimeDeltaBlock._box_func + other = Timedelta(other, unit='ns') + 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 fb381a56405191..47b08a01103ef4 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,16 @@ 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): + expected = pd.DataFrame([pd.Timestamp('2018-01-02')]) + result = pd.DataFrame([pd.Timestamp('2018-01-01')]) + other + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize('data', [ [1, 2, 3], [1.1, 2.2, 3.3],