Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -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
--------------

Expand Down
18 changes: 10 additions & 8 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'(?<![a-z])am\b', lowered):
hour = 0
if len(numbers) > 1:
minute = int(numbers[indexes['M']])
if len(numbers) > 2:
Expand Down
8 changes: 8 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down