Skip to content

Commit 367a5a2

Browse files
Backport PR #52220 on branch 2.0.x (BUG: zero-pad shorter years in Timestamp.isoformat) (#52327)
Backport PR #52220: BUG: zero-pad shorter years in `Timestamp.isoformat` Co-authored-by: Justus Magin <[email protected]>
1 parent 845a38b commit 367a5a2

File tree

3 files changed

+16
-13
lines changed

3 files changed

+16
-13
lines changed

pandas/_libs/tslibs/timestamps.pyx

+1-1
Original file line numberDiff line numberDiff line change
@@ -1012,7 +1012,7 @@ cdef class _Timestamp(ABCTimestamp):
10121012
base_ts = "microseconds" if timespec == "nanoseconds" else timespec
10131013
base = super(_Timestamp, self).isoformat(sep=sep, timespec=base_ts)
10141014
# We need to replace the fake year 1970 with our real year
1015-
base = f"{self.year}-" + base.split("-", 1)[1]
1015+
base = f"{self.year:04d}-" + base.split("-", 1)[1]
10161016

10171017
if self.nanosecond == 0 and timespec != "nanoseconds":
10181018
return base

pandas/tests/scalar/timestamp/test_constructors.py

+4-12
Original file line numberDiff line numberDiff line change
@@ -593,21 +593,13 @@ def test_bounds_with_different_units(self):
593593
@pytest.mark.parametrize("arg", ["001-01-01", "0001-01-01"])
594594
def test_out_of_bounds_string_consistency(self, arg):
595595
# GH 15829
596-
msg = "|".join(
597-
[
598-
"Cannot cast 1-01-01 00:00:00 to unit='ns' without overflow",
599-
"Out of bounds nanosecond timestamp: 1-01-01 00:00:00",
600-
]
601-
)
596+
msg = "Cannot cast 0001-01-01 00:00:00 to unit='ns' without overflow"
602597
with pytest.raises(OutOfBoundsDatetime, match=msg):
603598
Timestamp(arg).as_unit("ns")
604599

605-
if arg == "0001-01-01":
606-
# only the 4-digit year goes through ISO path which gets second reso
607-
# instead of ns reso
608-
ts = Timestamp(arg)
609-
assert ts.unit == "s"
610-
assert ts.year == ts.month == ts.day == 1
600+
ts = Timestamp(arg)
601+
assert ts.unit == "s"
602+
assert ts.year == ts.month == ts.day == 1
611603

612604
def test_min_valid(self):
613605
# Ensure that Timestamp.min is a valid Timestamp

pandas/tests/scalar/timestamp/test_formats.py

+11
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,15 @@
1111
second=8,
1212
microsecond=132263,
1313
)
14+
ts_no_ns_year1 = Timestamp(
15+
year=1,
16+
month=5,
17+
day=18,
18+
hour=15,
19+
minute=17,
20+
second=8,
21+
microsecond=132263,
22+
)
1423
ts_ns = Timestamp(
1524
year=2019,
1625
month=5,
@@ -50,6 +59,8 @@
5059
(ts_no_ns, "auto", "2019-05-18T15:17:08.132263"),
5160
(ts_no_ns, "seconds", "2019-05-18T15:17:08"),
5261
(ts_no_ns, "nanoseconds", "2019-05-18T15:17:08.132263000"),
62+
(ts_no_ns_year1, "seconds", "0001-05-18T15:17:08"),
63+
(ts_no_ns_year1, "nanoseconds", "0001-05-18T15:17:08.132263000"),
5364
(ts_ns, "auto", "2019-05-18T15:17:08.132263123"),
5465
(ts_ns, "hours", "2019-05-18T15"),
5566
(ts_ns, "minutes", "2019-05-18T15:17"),

0 commit comments

Comments
 (0)