Skip to content

Commit 81059e5

Browse files
committed
gh-162812: fix strptime in locales with empty am and pm markers
An omitted period marker compares equal to an empty PM string. Require a nonempty marker before selecting the PM branch.
1 parent 9d66e0c commit 81059e5

3 files changed

Lines changed: 14 additions & 1 deletion

File tree

‎Lib/_strptime.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ def parse_int(s):
646646
hour = parse_int(found_dict['I'])
647647
ampm = found_dict.get('p', '').lower()
648648
# If there was no AM/PM indicator, we'll treat this like AM
649-
if ampm == locale_time.am_pm[1]:
649+
if ampm and ampm == locale_time.am_pm[1]:
650650
# We're in PM so we need to add 12 to the hour unless
651651
# we're looking at 12 noon.
652652
# 12 noon == 12 PM == hour 12

‎Lib/test/test_strptime.py‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,17 @@ def test_strptime_n_and_t_format(self):
709709
class Strptime12AMPMTests(unittest.TestCase):
710710
"""Test a _strptime regression in '%I %p' at 12 noon (12 PM)"""
711711

712+
def test_empty_am_pm(self):
713+
locale_time = _strptime.LocaleTime()
714+
locale_time.am_pm = ('', '')
715+
time_re = _strptime.TimeRE(locale_time)
716+
with (
717+
support.swap_attr(_strptime, '_TimeRE_cache', time_re),
718+
support.swap_attr(_strptime, '_regex_cache', {}),
719+
):
720+
self.assertEqual(time.strptime('01', '%I').tm_hour, 1)
721+
self.assertEqual(time.strptime('12', '%I').tm_hour, 0)
722+
712723
def test_twelve_noon_midnight(self):
713724
eq = self.assertEqual
714725
eq(time.strptime('12 PM', '%I %p')[3], 12)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :func:`time.strptime` interpreting 12-hour times as PM in locales
2+
with empty AM and PM strings.

0 commit comments

Comments
 (0)