]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-152305: Fix `_pydatetime.time.strftime()` raising on year directives (#152306)
authortonghuaroot (童话) <tonghuaroot@gmail.com>
Sat, 27 Jun 2026 15:07:32 +0000 (23:07 +0800)
committerGitHub <noreply@github.com>
Sat, 27 Jun 2026 15:07:32 +0000 (16:07 +0100)
Co-authored-by: Stan Ulbrych <stan@python.org>
Lib/_pydatetime.py
Lib/test/datetimetester.py
Misc/NEWS.d/next/Library/2026-06-26-15-41-34.gh-issue-152305.WnbbBc.rst [new file with mode: 0644]

index db4ea8d30c7064ff36d4af6a36e936fdc3db0b78..c47f4e671b39def8fdd90a141985b3ce5a168f35 100644 (file)
@@ -272,12 +272,12 @@ def _wrap_strftime(object, format, timetuple):
                     newformat.append(Zreplace)
                 # Note that datetime(1000, 1, 1).strftime('%G') == '1000' so
                 # year 1000 for %G can go on the fast path.
-                elif ((ch in 'YG' or ch in 'FC') and
-                        object.year < 1000 and _need_normalize_century()):
+                elif (ch in 'YGFC' and timetuple[0] < 1000 and
+                        _need_normalize_century()):
                     if ch == 'G':
                         year = int(_time.strftime("%G", timetuple))
                     else:
-                        year = object.year
+                        year = timetuple[0]
                     if ch == 'C':
                         push('{:02}'.format(year // 100))
                     else:
index 28c3ab2605c45dbe690c3ac991097ba84304436d..192b22ff7540034ef89ade524da7eb5f9013a4d4 100644 (file)
@@ -4119,6 +4119,11 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
         self.assertEqual(t.strftime('\0'*1000), '\0'*1000)
         self.assertEqual(t.strftime('\0%I%p%Z\0%X'), f'\0{s1}\0{s2}')
         self.assertEqual(t.strftime('%I%p%Z\0%X\0'), f'{s1}\0{s2}\0')
+        # gh-152305: the year directives must not raise on a time.
+        for directive, expected in (('%Y', '1900'), ('%G', '1900'),
+                                    ('%C', '19'), ('%F', '1900-01-01')):
+            with self.subTest(directive=directive):
+                self.assertEqual(t.strftime(directive), expected)
 
     def test_format(self):
         t = self.theclass(1, 2, 3, 4)
diff --git a/Misc/NEWS.d/next/Library/2026-06-26-15-41-34.gh-issue-152305.WnbbBc.rst b/Misc/NEWS.d/next/Library/2026-06-26-15-41-34.gh-issue-152305.WnbbBc.rst
new file mode 100644 (file)
index 0000000..4f27e2e
--- /dev/null
@@ -0,0 +1,2 @@
+Fix the pure-Python :meth:`datetime.time.strftime` implementation raising :exc:`AttributeError` for the
+year directives. Patch by tonghuaroot.