Skip to content

fix: show correct error message when invalid period alias is passed to to_timestamp #59373

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion doc/source/whatsnew/v3.0.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ I/O

Period
^^^^^^
-
- Fixed error message when passing invalid period alias to :meth:`PeriodIndex.to_timestamp` (:issue:`58974`)
-

Plotting
Expand Down
24 changes: 10 additions & 14 deletions pandas/_libs/tslibs/offsets.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4752,20 +4752,16 @@ def _validate_to_offset_alias(alias: str, is_period: bool) -> None:
alias.lower() not in {"s", "ms", "us", "ns"} and
alias.upper().split("-")[0].endswith(("S", "E"))):
raise ValueError(INVALID_FREQ_ERR_MSG.format(alias))
if (is_period and
alias.upper() in c_OFFSET_TO_PERIOD_FREQSTR and
alias != "ms" and
alias.upper().split("-")[0].endswith(("S", "E"))):
if (alias.upper().startswith("B") or
alias.upper().startswith("S") or
alias.upper().startswith("C")):
raise ValueError(INVALID_FREQ_ERR_MSG.format(alias))
else:
alias_msg = "".join(alias.upper().split("E", 1))
raise ValueError(
f"for Period, please use \'{alias_msg}\' "
f"instead of \'{alias}\'"
)
if (
is_period and
alias in c_OFFSET_TO_PERIOD_FREQSTR and
alias != c_OFFSET_TO_PERIOD_FREQSTR[alias]
):
alias_msg = c_OFFSET_TO_PERIOD_FREQSTR.get(alias)
raise ValueError(
f"for Period, please use \'{alias_msg}\' "
f"instead of \'{alias}\'"
)


# TODO: better name?
Expand Down
7 changes: 7 additions & 0 deletions pandas/tests/indexes/period/methods/test_to_timestamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,10 @@ def test_to_timestamp_1703(self):

result = index.to_timestamp()
assert result[0] == Timestamp("1/1/2012")


def test_ms_to_timestamp_error_message():
# https://github.com/pandas-dev/pandas/issues/58974#issuecomment-2164265446
ix = period_range("2000", periods=3, freq="M")
with pytest.raises(ValueError, match="for Period, please use 'M' instead of 'MS'"):
ix.to_timestamp("MS")
Loading