Skip to content

Commit 79900d0

Browse files
author
MarcoGorelli
committed
raise error if strftime called on out-of-python-range timestamps
1 parent 06d074f commit 79900d0

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

pandas/_libs/tslibs/timestamps.pyx

+9-1
Original file line numberDiff line numberDiff line change
@@ -1409,7 +1409,15 @@ class Timestamp(_Timestamp):
14091409
>>> ts.strftime('%Y-%m-%d %X')
14101410
'2020-03-14 15:32:52'
14111411
"""
1412-
return datetime.strftime(self, format)
1412+
try:
1413+
return self.to_pydatetime().strftime(format)
1414+
except ValueError as err:
1415+
raise ValueError(
1416+
"strftime not yet supported on Timestamps which "
1417+
"are outside the range of Python's standard library. "
1418+
"For now, please call the components you need (such as `.year` "
1419+
"and `.month`) and construct your string from there."
1420+
)
14131421

14141422
# Issue 25016.
14151423
@classmethod

pandas/tests/scalar/timestamp/test_timestamp.py

+12
Original file line numberDiff line numberDiff line change
@@ -1104,3 +1104,15 @@ def test_utctimetuple():
11041104
result = ts.utctimetuple()
11051105
expected = time.struct_time((2000, 1, 1, 0, 0, 0, 5, 1, 0))
11061106
assert result == expected
1107+
1108+
1109+
def test_negative_dates():
1110+
# https://github.com/pandas-dev/pandas/issues/50787
1111+
ts = Timestamp("-2000-01-01")
1112+
msg = (
1113+
"^strftime not yet supported on Timestamps which are outside the range of "
1114+
"Python's standard library. For now, please call the components you need "
1115+
r"\(such as `.year` and `.month`\) and construct your string from there.$"
1116+
)
1117+
with pytest.raises(ValueError, match=msg):
1118+
ts.strftime("%Y")

0 commit comments

Comments
 (0)