Skip to content

Commit 0f088f5

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

File tree

2 files changed

+20
-7
lines changed

2 files changed

+20
-7
lines changed

pandas/core/arrays/datetimes.py

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -817,14 +817,27 @@ def _add_offset(self, offset: BaseOffset) -> Self:
817817
result = type(self)._from_sequence(res_values, dtype=self.dtype)
818818

819819
else:
820-
units = ["ns", "us", "ms", "s", "m", "h", "D"]
820+
units = [
821+
"ns",
822+
"us",
823+
"ms",
824+
"s",
825+
]
821826
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+
# Only try to adjust unit if both units are recognized
828+
try:
829+
if hasattr(offset, "offset"):
830+
offset_td = Timedelta(offset.offset)
831+
offset_unit = offset_td.unit
832+
if self.unit in units and offset_unit in units:
833+
idx_self = units.index(self.unit)
834+
idx_offset = units.index(offset_unit)
835+
res_unit = units[min(idx_self, idx_offset)]
836+
except Exception:
837+
res_unit = self.unit
827838
dtype = tz_to_dtype(self.tz, unit=res_unit)
839+
if res_values.dtype != f"datetime64[{res_unit}]":
840+
res_values = res_values.astype(f"datetime64[{res_unit}]")
828841
result = type(self)._simple_new(res_values, dtype=dtype)
829842

830843
if offset.normalize:

pandas/tests/arrays/test_datetimes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -860,4 +860,4 @@ def test_dt64_non_nano_offset_no_rounding():
860860
pd.Timestamp("2016-01-04 00:00:00.001"),
861861
]
862862
)
863-
assert all(result == expected)
863+
tm.assert_index_equal(result, expected)

0 commit comments

Comments
 (0)