gh-120713: Normalize year with century for datetime.strftime (GH-120820)

This commit is contained in:
blhsing 2024-06-29 14:32:42 +08:00 committed by GitHub
parent 92893fd8dc
commit 6d34938dc8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 174 additions and 16 deletions

View file

@ -1697,18 +1697,26 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
self.assertTrue(self.theclass.max)
def test_strftime_y2k(self):
for y in (1, 49, 70, 99, 100, 999, 1000, 1970):
d = self.theclass(y, 1, 1)
# Issue 13305: For years < 1000, the value is not always
# padded to 4 digits across platforms. The C standard
# assumes year >= 1900, so it does not specify the number
# of digits.
if d.strftime("%Y") != '%04d' % y:
# Year 42 returns '42', not padded
self.assertEqual(d.strftime("%Y"), '%d' % y)
# '0042' is obtained anyway
if support.has_strftime_extensions:
self.assertEqual(d.strftime("%4Y"), '%04d' % y)
# Test that years less than 1000 are 0-padded; note that the beginning
# of an ISO 8601 year may fall in an ISO week of the year before, and
# therefore needs an offset of -1 when formatting with '%G'.
dataset = (
(1, 0),
(49, -1),
(70, 0),
(99, 0),
(100, -1),
(999, 0),
(1000, 0),
(1970, 0),
)
for year, offset in dataset:
for specifier in 'YG':
with self.subTest(year=year, specifier=specifier):
d = self.theclass(year, 1, 1)
if specifier == 'G':
year += offset
self.assertEqual(d.strftime(f"%{specifier}"), f"{year:04d}")
def test_replace(self):
cls = self.theclass