Skip to content

Commit 184ad31

Browse files
committed
BUG: Fix dt64[non_nano] + offset rounding
1 parent b2a6d74 commit 184ad31

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

pandas/core/arrays/datetimes.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,16 @@ def _add_offset(self, offset: BaseOffset) -> Self:
817817
result = type(self)._from_sequence(res_values, dtype=self.dtype)
818818

819819
else:
820-
result = type(self)._simple_new(res_values, dtype=res_values.dtype)
820+
units = ["ns", "us", "ms", "s", "m", "h", "D"]
821+
res_unit = self.unit
822+
if hasattr(offset, "offset"):
823+
offset_unit = Timedelta(offset.offset).unit
824+
idx_self = units.index(self.unit)
825+
idx_offset = units.index(offset_unit)
826+
res_unit = units[min(idx_self, idx_offset)]
827+
dtype = tz_to_dtype(self.tz, unit=res_unit)
828+
result = type(self)._simple_new(res_values, dtype=dtype)
829+
821830
if offset.normalize:
822831
result = result.normalize()
823832
result._freq = None

pandas/tests/arrays/test_datetimes.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -844,3 +844,20 @@ def test_factorize_sort_without_freq():
844844
tda = dta - dta[0]
845845
with pytest.raises(NotImplementedError, match=msg):
846846
tda.factorize(sort=True)
847+
848+
849+
def test_dt64_non_nano_offset_no_rounding():
850+
# GH#56586
851+
dti = pd.date_range("2016-01-01", periods=3, unit="s")
852+
offset = pd.offsets.CustomBusinessDay(offset=pd.Timedelta("1ms"))
853+
result = dti + offset
854+
855+
assert result.dtype == np.dtype("datetime64[ms]")
856+
expected = pd.DatetimeIndex(
857+
[
858+
pd.Timestamp("2016-01-02 00:00:00.001"),
859+
pd.Timestamp("2016-01-03 00:00:00.001"),
860+
pd.Timestamp("2016-01-04 00:00:00.001"),
861+
]
862+
)
863+
assert all(result == expected)

0 commit comments

Comments
 (0)