From 053a2f3e4ccefb5d5ca0f04f853de066eb37174d Mon Sep 17 00:00:00 2001 From: Twiink Date: Wed, 18 Nov 2026 15:17:55 +0800 Subject: [PATCH] =?UTF-8?q?fix(dates):=20=E4=BF=AE=E5=A4=8D=E4=B8=8D?= =?UTF-8?q?=E5=90=AB=E5=88=86=E9=92=9F=E7=9A=84=E6=97=B6=E9=97=B4=E6=A0=BC?= =?UTF-8?q?=E5=BC=8F=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- babel/dates.py | 11 ++++++----- tests/test_dates.py | 14 ++++++++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/babel/dates.py b/babel/dates.py index 6f810c1d5..4632a4efd 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -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 @@ -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: diff --git a/tests/test_dates.py b/tests/test_dates.py index 76a002bc3..7b2ef8dc3 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -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)