Skip to content

BUG: preserve DTA/TDA+timedeltalike scalar with mismatched resos #48923

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 17 commits into from
Oct 11, 2022
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1926,6 +1926,7 @@ class Timedelta(_Timedelta):
def __floordiv__(self, other):
# numpy does not implement floordiv for timedelta64 dtype, so we cannot
# just defer
orig = other
if _should_cast_to_timedelta(other):
# We interpret NaT as timedelta64("NaT")
other = Timedelta(other)
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/arrays/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -1275,7 +1275,9 @@ def _add_timedeltalike_scalar(self, other):

# PeriodArray overrides, so we only get here with DTA/TDA
self = cast("DatetimeArray | TimedeltaArray", self)
other = Timedelta(other)._as_unit(self._unit)
other = Timedelta(other)

self, other = self._ensure_matching_resos(other)
return self._add_timedeltalike(other)

def _add_timedelta_arraylike(self, other: TimedeltaArray):
Expand Down
7 changes: 7 additions & 0 deletions pandas/core/construction.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,13 @@ def array(

data = extract_array(data, extract_numpy=True)

if isinstance(data, ExtensionArray) and (
dtype is None or is_dtype_equal(dtype, data.dtype)
):
if copy:
return data.copy()
return data

# this returns None for not-found dtypes.
if isinstance(dtype, str):
dtype = registry.find(dtype) or dtype
Expand Down
35 changes: 34 additions & 1 deletion pandas/tests/arrays/test_datetimes.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
"""
Tests for DatetimeArray
"""
from datetime import timedelta
import operator

import numpy as np
import pytest

from pandas._libs.tslibs import tz_compare
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
from pandas._libs.tslibs.dtypes import (
NpyDatetimeUnit,
npy_unit_to_abbrev,
)

from pandas.core.dtypes.dtypes import DatetimeTZDtype

Expand Down Expand Up @@ -221,6 +225,35 @@ def test_add_mismatched_reso_doesnt_downcast(self):
# (so we _could_ downcast to unit="s"), we do not.
assert res._unit == "us"

@pytest.mark.parametrize(
"scalar",
[
timedelta(hours=2),
pd.Timedelta(hours=2),
np.timedelta64(2, "h"),
np.timedelta64(2 * 3600 * 1000, "ms"),
pd.offsets.Minute(120),
pd.offsets.Hour(2),
],
)
def test_add_timedeltalike_scalar_mismatched_reso(self, dta_dti, scalar):
dta, dti = dta_dti

td = pd.Timedelta(scalar)
exp_reso = max(dta._reso, td._reso)
exp_unit = npy_unit_to_abbrev(exp_reso)

expected = (dti + td)._data._as_unit(exp_unit)
result = dta + scalar
tm.assert_extension_array_equal(result, expected)

result = scalar + dta
tm.assert_extension_array_equal(result, expected)

expected = (dti - td)._data._as_unit(exp_unit)
result = dta - scalar
tm.assert_extension_array_equal(result, expected)

def test_sub_datetimelike_scalar_mismatch(self):
dti = pd.date_range("2016-01-01", periods=3)
dta = dti._data._as_unit("us")
Expand Down
3 changes: 2 additions & 1 deletion pandas/tests/scalar/timedelta/test_timedelta.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,8 @@ def test_truediv_timedeltalike(self, td):
assert (2.5 * td) / td == 2.5

other = Timedelta(td.value)
msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow."

msg = "Cannot cast 106752 days 00:00:00 to unit='ns' without overflow"
with pytest.raises(OutOfBoundsTimedelta, match=msg):
td / other

Expand Down
7 changes: 6 additions & 1 deletion pandas/tests/tseries/offsets/test_offsets.py
Original file line number Diff line number Diff line change
Expand Up @@ -576,8 +576,13 @@ def test_add_dt64_ndarray_non_nano(self, offset_types, unit, request):
)
request.node.add_marker(mark)

# result.dtype should match M8[{unit}], while expected.dtype should
# always be in nanos
# (this is for cases when offset_types is not itself Nano)
assert result.dtype != expected.dtype

tm.assert_numpy_array_equal(
result._ndarray, expected._ndarray.astype(arr.dtype)
result._ndarray, expected._ndarray.astype(result.dtype)
)


Expand Down