Skip to content

Commit

Permalink
Make seconds optional in parse_time time formats (#1141)
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasr8 authored Oct 20, 2024
1 parent f1c8633 commit e956b28
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 4 additions & 1 deletion babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from __future__ import annotations

import math
import re
import warnings
from functools import lru_cache
Expand Down Expand Up @@ -1281,7 +1282,9 @@ def parse_time(
if hour_idx < 0:
hour_idx = format_str.index('k')
min_idx = format_str.index('m')
sec_idx = format_str.index('s')
# format might not contain seconds
if (sec_idx := format_str.find('s')) < 0:
sec_idx = math.inf

indexes = sorted([(hour_idx, 'H'), (min_idx, 'M'), (sec_idx, 'S')])
indexes = {item[1]: idx for idx, item in enumerate(indexes)}
Expand Down
8 changes: 8 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,14 @@ def test_parse_time(input, expected):
assert dates.parse_time(input, locale='en_US') == expected


def test_parse_time_no_seconds_in_format():
# parse time using a time format which does not include seconds
locale = 'cs_CZ'
fmt = 'short'
assert dates.get_time_format(format=fmt, locale=locale).pattern == 'H:mm'
assert dates.parse_time('9:30', locale=locale, format=fmt) == time(9, 30)


def test_parse_time_alternate_characters(monkeypatch):
# 'K' can be used as an alternative to 'H'
def get_time_format(*args, **kwargs):
Expand Down

0 comments on commit e956b28

Please sign in to comment.