]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-81148: Eliminate unnecessary check in _strptime when determining AM/PM (#13428)
authorGordon P. Hemsley <me@gphemsley.org>
Fri, 19 Sep 2025 10:23:12 +0000 (06:23 -0400)
committerGitHub <noreply@github.com>
Fri, 19 Sep 2025 10:23:12 +0000 (10:23 +0000)
* bpo-36967: Eliminate unnecessary check in _strptime when determining AM/PM

* Pauls suggestion to refactor test

* Fix test

---------

Co-authored-by: Stan Ulbrych <89152624+StanFromIreland@users.noreply.github.com>
Co-authored-by: Paul Ganssle <1377457+pganssle@users.noreply.github.com>
Lib/_strptime.py
Lib/test/datetimetester.py

index a0117493954956f32748eb1075565cbf1bf4e227..d011ddf8b181c3ceb31f9d2987560fbdba4038be 100644 (file)
@@ -627,18 +627,18 @@ def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
             hour = parse_int(found_dict['I'])
             ampm = found_dict.get('p', '').lower()
             # If there was no AM/PM indicator, we'll treat this like AM
-            if ampm in ('', locale_time.am_pm[0]):
-                # We're in AM so the hour is correct unless we're
-                # looking at 12 midnight.
-                # 12 midnight == 12 AM == hour 0
-                if hour == 12:
-                    hour = 0
-            elif ampm == locale_time.am_pm[1]:
+            if ampm == locale_time.am_pm[1]:
                 # We're in PM so we need to add 12 to the hour unless
                 # we're looking at 12 noon.
                 # 12 noon == 12 PM == hour 12
                 if hour != 12:
                     hour += 12
+            else:
+                # We're in AM so the hour is correct unless we're
+                # looking at 12 midnight.
+                # 12 midnight == 12 AM == hour 0
+                if hour == 12:
+                    hour = 0
         elif group_key == 'M':
             minute = parse_int(found_dict['M'])
         elif group_key == 'S':
index 55cf1fa6bee6c3672be2f0c18298352b704a60dd..43cea44bc3d6c044b8de0a23316ae13ac3a493b5 100644 (file)
@@ -2942,6 +2942,16 @@ class TestDateTime(TestDate):
         with self.assertRaises(ValueError): strptime("-000", "%z")
         with self.assertRaises(ValueError): strptime("z", "%z")
 
+    def test_strptime_ampm(self):
+        dt = datetime(1999, 3, 17, 0, 44, 55, 2)
+        for hour in range(0, 24):
+            with self.subTest(hour=hour):
+                new_dt = dt.replace(hour=hour)
+                dt_str = new_dt.strftime("%I %p")
+
+                self.assertEqual(self.theclass.strptime(dt_str, "%I %p").hour,
+                                 hour)
+
     def test_strptime_single_digit(self):
         # bpo-34903: Check that single digit dates and times are allowed.