From bd91aae6ac85d62ce02291810c071b4deca7ea13 Mon Sep 17 00:00:00 2001 From: MarcoGorelli <> Date: Tue, 17 Jan 2023 15:43:05 +0000 Subject: [PATCH] raise error if strftime called on out-of-python-range timestamps --- pandas/_libs/tslibs/timestamps.pyx | 10 +++++++++- pandas/tests/scalar/timestamp/test_timestamp.py | 12 ++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 0da8a9e73d963c..308b92a4abaf08 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -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 diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 70f9f7c9248443..cbbb805f313ecf 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -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")