Skip to content

Commit e3d9bd6

Browse files
GPHemsleyStanFromIrelandpganssle
authored
gh-81148: Eliminate unnecessary check in _strptime when determining AM/PM (#13428)
* bpo-36967: Eliminate unnecessary check in _strptime when determining AM/PM * Pauls suggestion to refactor test * Fix test --------- Co-authored-by: Stan Ulbrych <[email protected]> Co-authored-by: Paul Ganssle <[email protected]>
1 parent 85c1ef6 commit e3d9bd6

File tree

2 files changed

+17
-7
lines changed

2 files changed

+17
-7
lines changed

Lib/_strptime.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -627,18 +627,18 @@ def parse_int(s):
627627
hour = parse_int(found_dict['I'])
628628
ampm = found_dict.get('p', '').lower()
629629
# If there was no AM/PM indicator, we'll treat this like AM
630-
if ampm in ('', locale_time.am_pm[0]):
631-
# We're in AM so the hour is correct unless we're
632-
# looking at 12 midnight.
633-
# 12 midnight == 12 AM == hour 0
634-
if hour == 12:
635-
hour = 0
636-
elif ampm == locale_time.am_pm[1]:
630+
if ampm == locale_time.am_pm[1]:
637631
# We're in PM so we need to add 12 to the hour unless
638632
# we're looking at 12 noon.
639633
# 12 noon == 12 PM == hour 12
640634
if hour != 12:
641635
hour += 12
636+
else:
637+
# We're in AM so the hour is correct unless we're
638+
# looking at 12 midnight.
639+
# 12 midnight == 12 AM == hour 0
640+
if hour == 12:
641+
hour = 0
642642
elif group_key == 'M':
643643
minute = parse_int(found_dict['M'])
644644
elif group_key == 'S':

Lib/test/datetimetester.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2942,6 +2942,16 @@ def test_strptime(self):
29422942
with self.assertRaises(ValueError): strptime("-000", "%z")
29432943
with self.assertRaises(ValueError): strptime("z", "%z")
29442944

2945+
def test_strptime_ampm(self):
2946+
dt = datetime(1999, 3, 17, 0, 44, 55, 2)
2947+
for hour in range(0, 24):
2948+
with self.subTest(hour=hour):
2949+
new_dt = dt.replace(hour=hour)
2950+
dt_str = new_dt.strftime("%I %p")
2951+
2952+
self.assertEqual(self.theclass.strptime(dt_str, "%I %p").hour,
2953+
hour)
2954+
29452955
def test_strptime_single_digit(self):
29462956
# bpo-34903: Check that single digit dates and times are allowed.
29472957

0 commit comments

Comments
 (0)