Skip to content

Commit

Permalink
fix: show correct error message when invalid period alias is passed t…
Browse files Browse the repository at this point in the history
…o to_timestamp (#59373)
  • Loading branch information
MarcoGorelli authored Aug 1, 2024
1 parent 6adba55 commit 7ee1091
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 15 deletions.
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 @@ -589,7 +589,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")

0 comments on commit 7ee1091

Please sign in to comment.