From d3ed92b266d3980ede90be81b04d6e50bf001c80 Mon Sep 17 00:00:00 2001 From: Marco Edward Gorelli <33491632+MarcoGorelli@users.noreply.github.com> Date: Wed, 18 Jan 2023 19:31:29 +0000 Subject: [PATCH] BUG: non-nano strftime returns wrong results (#50793) * catch error in strftime * noop Co-authored-by: MarcoGorelli <> --- pandas/_libs/tslibs/timestamps.pyx | 13 ++++++++++++- pandas/tests/scalar/timestamp/test_timestamp.py | 12 ++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 0da8a9e73d963..c1aef2e5115ac 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1409,7 +1409,18 @@ class Timestamp(_Timestamp): >>> ts.strftime('%Y-%m-%d %X') '2020-03-14 15:32:52' """ - return datetime.strftime(self, format) + try: + _dt = datetime(self.year, self.month, self.day, + self.hour, self.minute, self.second, + self.microsecond, self.tzinfo, fold=self.fold) + except ValueError as err: + raise NotImplementedError( + "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." + ) from err + return _dt.strftime(format) # Issue 25016. @classmethod diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 70f9f7c924844..22f5286569c6e 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(NotImplementedError, match=msg): + ts.strftime("%Y")