Skip to content

Commit

Permalink
raise error if strftime called on out-of-python-range timestamps
Browse files Browse the repository at this point in the history
  • Loading branch information
MarcoGorelli committed Jan 17, 2023
1 parent affcdf9 commit bd91aae
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pandas/_libs/tslibs/timestamps.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1409,7 +1409,15 @@ class Timestamp(_Timestamp):
>>> ts.strftime('%Y-%m-%d %X')
'2020-03-14 15:32:52'
"""
return datetime.strftime(self, format)
try:
return self.to_pydatetime().strftime(format)
except ValueError as err:
raise ValueError(
"strftime not yet supported on Timestamps which "
"are outside the range of Python's standard library. "
"For now, please call the components you need (such as `.year` "
"and `.month`) and construct your string from there."
)

# Issue 25016.
@classmethod
Expand Down
12 changes: 12 additions & 0 deletions pandas/tests/scalar/timestamp/test_timestamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1104,3 +1104,15 @@ def test_utctimetuple():
result = ts.utctimetuple()
expected = time.struct_time((2000, 1, 1, 0, 0, 0, 5, 1, 0))
assert result == expected


def test_negative_dates():
# https://github.com/pandas-dev/pandas/issues/50787
ts = Timestamp("-2000-01-01")
msg = (
"^strftime not yet supported on Timestamps which are outside the range of "
"Python's standard library. For now, please call the components you need "
r"\(such as `.year` and `.month`\) and construct your string from there.$"
)
with pytest.raises(ValueError, match=msg):
ts.strftime("%Y")

0 comments on commit bd91aae

Please sign in to comment.