Skip to content
Open
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
14 changes: 9 additions & 5 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1375,14 +1375,18 @@ 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
# if it does, convert the hour from the 12-hour clock, on which
# 12 AM and 12 PM are 00:00 and 12:00 respectively.
hour = int(numbers[indexes['H']])
if 'a' in format_str:
if 'pm' in string.lower():
if hour != 12:
hour += 12
elif 'am' in string.lower() and hour == 12:
hour = 0

# Parse up to three numbers from the string.
minute = second = 0
hour = int(numbers[indexes['H']]) + hour_offset
if len(numbers) > 1:
minute = int(numbers[indexes['M']])
if len(numbers) > 2:
Expand Down
6 changes: 6 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,12 @@ def test_parse_date_custom_format():
('03:30 PM', time(15, 30)),
# test hour-only parsing
('4 pm', time(16, 0)),
# test 12 o'clock am/pm conversion: noon and midnight
('12:00 pm', time(12, 0)),
('12:00 PM', time(12, 0)),
('12:30 am', time(0, 30)),
('12 AM', time(0, 0)),
('12:00:15 pm', time(12, 0, 15)),
],
)
def test_parse_time(input, expected):
Expand Down