diff --git a/CHANGES.rst b/CHANGES.rst index b09e184e8..114b3ecc5 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,14 @@ Babel Changelog =============== +Unreleased +---------- + +Bugfixes +~~~~~~~~ + +* Time: ``parse_time('12:00 AM')`` returned noon. 12 AM is midnight and 12 PM is noon. by @SashaMIT in :gh:`1357` + Version 2.18.0 -------------- diff --git a/babel/dates.py b/babel/dates.py index 7b626aa11..4a8284f64 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -1374,15 +1374,17 @@ def parse_time( # TODO: support time zones - # Check if the format specifies a period to be used; - # if it does, look for 'pm' to figure out an offset. - hour_offset = 0 - if 'a' in format_str and 'pm' in string.lower(): - hour_offset = 12 - - # Parse up to three numbers from the string. + # Check if the format specifies a period to be used. + # 12 AM is midnight and 12 PM is noon. Adding 12 to 12 made hour 24. minute = second = 0 - hour = int(numbers[indexes['H']]) + hour_offset + hour = int(numbers[indexes['H']]) + if 'a' in format_str: + lowered = string.lower() + if 'pm' in lowered: + if hour != 12: + hour += 12 + elif hour == 12 and re.search(r'(? 1: minute = int(numbers[indexes['M']]) if len(numbers) > 2: diff --git a/tests/test_dates.py b/tests/test_dates.py index 4f8c73907..af737b281 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -492,6 +492,14 @@ def test_parse_date_custom_format(): ('03:30 PM', time(15, 30)), # test hour-only parsing ('4 pm', time(16, 0)), + # 12 AM is midnight. 12 PM is noon. + ('12 am', time(0, 0)), + ('12 pm', time(12, 0)), + ('12:00 am', time(0, 0)), + ('12:00 pm', time(12, 0)), + ('12:30 AM', time(0, 30)), + ('12:30 PM', time(12, 30)), + ('12:30', time(12, 30)), ], ) def test_parse_time(input, expected):