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
11 changes: 6 additions & 5 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1508,8 +1508,9 @@ def parse_time(
hour_idx = format_str.find('h')
if hour_idx < 0:
hour_idx = format_str.index('k')
min_idx = format_str.index('m')
# format might not contain seconds
# Explicit patterns can omit minutes or seconds.
if (min_idx := format_str.find('m')) < 0:
min_idx = math.inf
if (sec_idx := format_str.find('s')) < 0:
sec_idx = math.inf

Expand All @@ -1531,10 +1532,10 @@ def parse_time(

# Parse up to three numbers from the string.
minute = second = 0
if len(numbers) > 1:
if indexes['M'] < len(numbers) and min_idx != math.inf:
minute = int(numbers[indexes['M']])
if len(numbers) > 2:
second = int(numbers[indexes['S']])
if indexes['S'] < len(numbers):
second = int(numbers[indexes['S']])
try:
return datetime.time(hour, minute, second)
except ValueError as e:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -795,6 +795,20 @@ def get_date_format(*args, **kwargs):
assert dates.parse_date('2024-10-20') == date(2024, 10, 20)


@pytest.mark.parametrize(
('pattern', 'locale', 'value'),
[
('HH', 'en', time(19)),
('H時', 'ja', time(6)),
('h a', 'en', time(15)),
('ss:HH', 'en', time(19, 0, 23)),
],
)
def test_parse_hour_without_minutes(pattern, locale, value):
text = dates.format_time(value, pattern, locale=locale)
assert dates.parse_time(text, format=pattern, locale=locale) == value


def test_parse_time_custom_format():
assert dates.parse_time('15:30:00', format='HH:mm:ss') == time(15, 30)
assert dates.parse_time('00:30:15', format='ss:mm:HH') == time(15, 30)
Expand Down