From: Tomas R. Date: Sun, 20 Oct 2024 06:50:36 +0000 (+0200) Subject: Make seconds optional in `parse_time` time formats (#1141) X-Git-Tag: v2.17.0~25 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e956b28b6813e35b136a6537871ffe2ab1eccb54;p=thirdparty%2Fbabel.git Make seconds optional in `parse_time` time formats (#1141) --- diff --git a/babel/dates.py b/babel/dates.py index 30321b76..2f1b116e 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -17,6 +17,7 @@ from __future__ import annotations +import math import re import warnings from functools import lru_cache @@ -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)} diff --git a/tests/test_dates.py b/tests/test_dates.py index 549929be..fef68ae7 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -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):