Skip to content

Commit 2edec6f

Browse files
mroeschkemeeseeksmachine
authored andcommitted
Backport PR pandas-dev#52841: BUG: dt.round with equal/higher freq resolution would not noop
1 parent 6d63392 commit 2edec6f

File tree

3 files changed

+18
-2
lines changed

3 files changed

+18
-2
lines changed

doc/source/whatsnew/v2.0.1.rst

+1
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ Bug fixes
2727
~~~~~~~~~
2828
- Bug in :attr:`Series.dt.days` that would overflow ``int32`` number of days (:issue:`52391`)
2929
- Bug in :class:`arrays.DatetimeArray` constructor returning an incorrect unit when passed a non-nanosecond numpy datetime array (:issue:`52555`)
30+
- Bug in :func:`Series.dt.round` when passing a ``freq`` of equal or higher resolution compared to the :class:`Series` would raise a ``ZeroDivisionError`` (:issue:`52761`)
3031
- Bug in :func:`Series.median` with :class:`ArrowDtype` returning an approximate median (:issue:`52679`)
3132
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on categorical dtypes (:issue:`49889`)
3233
- Bug in :func:`api.interchange.from_dataframe` was unnecessarily raising on large string dtypes (:issue:`52795`)

pandas/core/arrays/datetimelike.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -2005,8 +2005,12 @@ def _round(self, freq, mode, ambiguous, nonexistent):
20052005

20062006
values = self.view("i8")
20072007
values = cast(np.ndarray, values)
2008-
nanos = to_offset(freq).nanos # raises on non-fixed frequencies
2009-
nanos = delta_to_nanoseconds(to_offset(freq), self._creso)
2008+
offset = to_offset(freq)
2009+
offset.nanos # raises on non-fixed frequencies
2010+
nanos = delta_to_nanoseconds(offset, self._creso)
2011+
if nanos == 0:
2012+
# GH 52761
2013+
return self
20102014
result_i8 = round_nsint64(values, mode, nanos)
20112015
result = self._maybe_mask_results(result_i8, fill_value=iNaT)
20122016
result = result.view(self._ndarray.dtype)

pandas/tests/series/accessors/test_dt_accessor.py

+11
Original file line numberDiff line numberDiff line change
@@ -381,6 +381,17 @@ def test_dt_round_tz_nonexistent(self, method, ts_str, freq):
381381
with pytest.raises(pytz.NonExistentTimeError, match="2018-03-11 02:00:00"):
382382
getattr(ser.dt, method)(freq, nonexistent="raise")
383383

384+
@pytest.mark.parametrize("freq", ["ns", "U", "1000U"])
385+
def test_dt_round_nonnano_higher_resolution_no_op(self, freq):
386+
# GH 52761
387+
ser = Series(
388+
["2020-05-31 08:00:00", "2000-12-31 04:00:05", "1800-03-14 07:30:20"],
389+
dtype="datetime64[ms]",
390+
)
391+
expected = ser.copy()
392+
result = ser.dt.round(freq)
393+
tm.assert_series_equal(result, expected)
394+
384395
def test_dt_namespace_accessor_categorical(self):
385396
# GH 19468
386397
dti = DatetimeIndex(["20171111", "20181212"]).repeat(2)

0 commit comments

Comments
 (0)