Skip to content

Commit 7ee1091

Browse files
authored
fix: show correct error message when invalid period alias is passed to to_timestamp (#59373)
1 parent 6adba55 commit 7ee1091

File tree

3 files changed

+18
-15
lines changed

3 files changed

+18
-15
lines changed

doc/source/whatsnew/v3.0.0.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,7 @@ I/O
589589

590590
Period
591591
^^^^^^
592-
-
592+
- Fixed error message when passing invalid period alias to :meth:`PeriodIndex.to_timestamp` (:issue:`58974`)
593593
-
594594

595595
Plotting

pandas/_libs/tslibs/offsets.pyx

+10-14
Original file line numberDiff line numberDiff line change
@@ -4752,20 +4752,16 @@ def _validate_to_offset_alias(alias: str, is_period: bool) -> None:
47524752
alias.lower() not in {"s", "ms", "us", "ns"} and
47534753
alias.upper().split("-")[0].endswith(("S", "E"))):
47544754
raise ValueError(INVALID_FREQ_ERR_MSG.format(alias))
4755-
if (is_period and
4756-
alias.upper() in c_OFFSET_TO_PERIOD_FREQSTR and
4757-
alias != "ms" and
4758-
alias.upper().split("-")[0].endswith(("S", "E"))):
4759-
if (alias.upper().startswith("B") or
4760-
alias.upper().startswith("S") or
4761-
alias.upper().startswith("C")):
4762-
raise ValueError(INVALID_FREQ_ERR_MSG.format(alias))
4763-
else:
4764-
alias_msg = "".join(alias.upper().split("E", 1))
4765-
raise ValueError(
4766-
f"for Period, please use \'{alias_msg}\' "
4767-
f"instead of \'{alias}\'"
4768-
)
4755+
if (
4756+
is_period and
4757+
alias in c_OFFSET_TO_PERIOD_FREQSTR and
4758+
alias != c_OFFSET_TO_PERIOD_FREQSTR[alias]
4759+
):
4760+
alias_msg = c_OFFSET_TO_PERIOD_FREQSTR.get(alias)
4761+
raise ValueError(
4762+
f"for Period, please use \'{alias_msg}\' "
4763+
f"instead of \'{alias}\'"
4764+
)
47694765

47704766

47714767
# TODO: better name?

pandas/tests/indexes/period/methods/test_to_timestamp.py

+7
Original file line numberDiff line numberDiff line change
@@ -140,3 +140,10 @@ def test_to_timestamp_1703(self):
140140

141141
result = index.to_timestamp()
142142
assert result[0] == Timestamp("1/1/2012")
143+
144+
145+
def test_ms_to_timestamp_error_message():
146+
# https://github.com/pandas-dev/pandas/issues/58974#issuecomment-2164265446
147+
ix = period_range("2000", periods=3, freq="M")
148+
with pytest.raises(ValueError, match="for Period, please use 'M' instead of 'MS'"):
149+
ix.to_timestamp("MS")

0 commit comments

Comments
 (0)