Skip to content
31 changes: 22 additions & 9 deletions pandas/core/arrays/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@
)
from pandas.core.dtypes.missing import isna

from pandas import Timedelta
from pandas.core.arrays import datetimelike as dtl
from pandas.core.arrays._ranges import generate_regular_range
import pandas.core.common as com
Expand Down Expand Up @@ -93,7 +94,6 @@

from pandas import (
DataFrame,
Timedelta,
)
from pandas.core.arrays import PeriodArray

Expand Down Expand Up @@ -817,21 +817,34 @@ def _add_offset(self, offset: BaseOffset) -> Self:
result = type(self)._from_sequence(res_values, dtype=self.dtype)

else:
units = ["ns", "us", "ms", "s", "m", "h", "D"]
units = [
"ns",
"us",
"ms",
"s",
]
res_unit = self.unit
if hasattr(offset, "offset"):
offset_unit = Timedelta(offset.offset).unit
idx_self = units.index(self.unit)
idx_offset = units.index(offset_unit)
res_unit = units[min(idx_self, idx_offset)]
dtype = tz_to_dtype(self.tz, unit=res_unit)
result = type(self)._simple_new(res_values, dtype=dtype)
offset_td = Timedelta(offset.offset)
offset_unit = offset_td.unit
if self.unit in units and offset_unit in units:
idx_self = units.index(self.unit)
idx_offset = units.index(offset_unit)
res_unit = units[min(idx_self, idx_offset)]
dtype_naive = np.dtype(f"datetime64[{res_unit}]")
if res_values.dtype != dtype_naive:
res_values = res_values.astype(dtype_naive)
result = type(self)._simple_new(res_values, dtype=dtype_naive)

if offset.normalize:
result = result.normalize()
result._freq = None

if self.tz is not None:
if (
self.tz is not None
and getattr(result.dtype, "tz", None) is None
and res_unit == "ns"
):
result = result.tz_localize(self.tz)

return result
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/arrays/test_datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,4 +860,4 @@ def test_dt64_non_nano_offset_no_rounding():
pd.Timestamp("2016-01-04 00:00:00.001"),
]
)
assert all(result == expected)
tm.assert_index_equal(result, expected)
Loading