Skip to content

Commit 43d701e

Browse files
committed
core: fix DatetimeBlock operated with timedelta
1 parent 2c7c797 commit 43d701e

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

doc/source/whatsnew/v0.24.0.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,7 +443,7 @@ Datetimelike
443443
Timedelta
444444
^^^^^^^^^
445445

446-
-
446+
- Bug in :class:`DataFrame` with ``dtype='datetime64[ns]'`` when adding :class:`Timedelta` (:issue:`22007`)
447447
-
448448
-
449449

pandas/core/internals/blocks.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2713,6 +2713,11 @@ def _try_coerce_args(self, values, other):
27132713
"naive Block")
27142714
other_mask = isna(other)
27152715
other = other.asm8.view('i8')
2716+
elif isinstance(other, (timedelta, np.timedelta64)):
2717+
if not isinstance(other, Timedelta):
2718+
other = Timedelta(other)
2719+
other_mask = isna(other)
2720+
other = other.asm8.view('i8')
27162721
elif hasattr(other, 'dtype') and is_datetime64_dtype(other):
27172722
other_mask = isna(other)
27182723
other = other.astype('i8', copy=False).view('i8')

pandas/tests/frame/test_arithmetic.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
# -*- coding: utf-8 -*-
2+
import datetime
3+
24
import pytest
35
import numpy as np
46

@@ -211,6 +213,19 @@ def test_df_sub_datetime64_not_ns(self):
211213
pd.Timedelta(days=2)])
212214
tm.assert_frame_equal(res, expected)
213215

216+
@pytest.mark.parametrize('other', [
217+
pd.Timedelta('1d'),
218+
datetime.timedelta(days=1),
219+
np.timedelta64(1, 'D')
220+
])
221+
def test_timestamp_df_add_timedelta(self, other):
222+
expected = pd.DataFrame([pd.Timestamp('2018-01-02')])
223+
result = pd.DataFrame([pd.Timestamp('2018-01-01')]) + other
224+
tm.assert_frame_equal(result, expected)
225+
226+
result = other + pd.DataFrame([pd.Timestamp('2018-01-01')])
227+
tm.assert_frame_equal(result, expected)
228+
214229
@pytest.mark.parametrize('data', [
215230
[1, 2, 3],
216231
[1.1, 2.2, 3.3],

0 commit comments

Comments
 (0)