Skip to content

Commit 13dc13f

Browse files
authored
BUG: to_period() freq was not infered (#33406)
1 parent 6658d89 commit 13dc13f

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

doc/source/whatsnew/v1.1.0.rst

+2
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,8 @@ Datetimelike
410410
- Bug in :meth:`DatetimeIndex.searchsorted` not accepting a ``list`` or :class:`Series` as its argument (:issue:`32762`)
411411
- Bug where :meth:`PeriodIndex` raised when passed a :class:`Series` of strings (:issue:`26109`)
412412
- Bug in :class:`Timestamp` arithmetic when adding or subtracting a ``np.ndarray`` with ``timedelta64`` dtype (:issue:`33296`)
413+
- Bug in :meth:`DatetimeIndex.to_period` not infering the frequency when called with no arguments (:issue:`33358`)
414+
413415

414416
Timedelta
415417
^^^^^^^^^

pandas/core/arrays/datetimes.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
timezones,
1919
tzconversion,
2020
)
21+
import pandas._libs.tslibs.frequencies as libfrequencies
2122
from pandas.errors import PerformanceWarning
2223

2324
from pandas.core.dtypes.common import (
@@ -1097,7 +1098,14 @@ def to_period(self, freq=None):
10971098
"You must pass a freq argument as current index has none."
10981099
)
10991100

1100-
freq = get_period_alias(freq)
1101+
res = get_period_alias(freq)
1102+
1103+
# https://github.com/pandas-dev/pandas/issues/33358
1104+
if res is None:
1105+
base, stride = libfrequencies._base_and_stride(freq)
1106+
res = f"{stride}{base}"
1107+
1108+
freq = res
11011109

11021110
return PeriodArray._from_datetime64(self._data, freq, tz=self.tz)
11031111

pandas/tests/indexes/datetimes/test_to_period.py

+24
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import warnings
2+
13
import dateutil.tz
24
from dateutil.tz import tzlocal
35
import pytest
@@ -75,6 +77,28 @@ def test_to_period_monthish(self):
7577
with pytest.raises(ValueError, match=INVALID_FREQ_ERR_MSG):
7678
date_range("01-Jan-2012", periods=8, freq="EOM")
7779

80+
def test_to_period_infer(self):
81+
# https://github.com/pandas-dev/pandas/issues/33358
82+
rng = date_range(
83+
start="2019-12-22 06:40:00+00:00",
84+
end="2019-12-22 08:45:00+00:00",
85+
freq="5min",
86+
)
87+
88+
with tm.assert_produces_warning(None):
89+
# Using simple filter because we are not checking for the warning here
90+
warnings.simplefilter("ignore", UserWarning)
91+
92+
pi1 = rng.to_period("5min")
93+
94+
with tm.assert_produces_warning(None):
95+
# Using simple filter because we are not checking for the warning here
96+
warnings.simplefilter("ignore", UserWarning)
97+
98+
pi2 = rng.to_period()
99+
100+
tm.assert_index_equal(pi1, pi2)
101+
78102
def test_period_dt64_round_trip(self):
79103
dti = date_range("1/1/2000", "1/7/2002", freq="B")
80104
pi = dti.to_period()

0 commit comments

Comments
 (0)