From ec8d5216a1e73823a2bbe12dacb20dd2a1088764 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?As=C4=B1m=20Mirza=20=C3=87iftler?= Date: Tue, 24 Nov 2026 22:28:39 +0300 Subject: [PATCH] Parse month names in parse_date() parse_date() only read numbers, so dates in formats that spell out the month, which is the default medium format of en_US and most other locales, raised an IndexError, e.g. parse_date('Nov 24, 2026', locale='en_US'). Look for the locale's month names, then English ones, when the pattern has a textual month field. Names must be separate words unless the pattern attaches letters to the month (Hebrew, Basque, ...), and a match inside a day name is skipped (in Welsh "Mawrth" is Tuesday and March). Input with too few numbers now raises ParseError instead of IndexError. Co-Authored-By: Claude Opus 5.5 --- babel/dates.py | 117 +++++++++++++++++++++++++++++++++++++++++--- tests/test_dates.py | 41 ++++++++++++++++ 2 files changed, 151 insertions(+), 7 deletions(-) diff --git a/babel/dates.py b/babel/dates.py index 6f810c1d5..de254c9c1 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -1381,6 +1381,84 @@ def _expand_two_digit_year(year: int) -> int: return expanded +def _find_month_name( + string: str, + locale: Locale | str | None, + pattern: str, +) -> tuple[int, int, int] | None: + """Find a month name in `string`, parsed with the date `pattern`. + + Wide and abbreviated, format and stand-alone names of the locale are + tried first, then the English ones. Returns ``(month, start, end)`` or + ``None``. + + Longer names are preferred, so "March" is not read as "Mar". A name must + be a separate word, unless the pattern itself attaches letters to the + month (e.g. Hebrew puts a prefix letter before it, and Basque has + "MMMM'ren'"). A match that + is part of a day name is skipped if there is another one, because some + languages share names between days and months (in Welsh, "Mawrth" is + both Tuesday and March). + """ + locale = Locale.parse(locale or LC_TIME) + attached_before = attached_after = False + tokens = tokenize_pattern(pattern) + for i, (kind, value) in enumerate(tokens): + if kind == 'field' and value[0] in 'ML' and value[1] >= 3: + if i > 0 and tokens[i - 1][0] == 'chars': + attached_before = tokens[i - 1][1][-1:].isalpha() + if i + 1 < len(tokens) and tokens[i + 1][0] == 'chars': + attached_after = tokens[i + 1][1][:1].isalpha() + break + + day_regex, _ = _calendar_name_regex(str(locale), 'days', False, False) + day_spans = [m.span() for m in day_regex.finditer(string)] + + for loc, before, after in ((str(locale), attached_before, attached_after), ('en', False, False)): + regex, months = _calendar_name_regex(loc, 'months', before, after) + matches = [(months[m.lastindex - 1], m.start(), m.end()) for m in regex.finditer(string)] + if matches: + outside_days = [ + match for match in matches + if not any(start <= match[1] and match[2] <= end for start, end in day_spans) + ] + return (outside_days or matches)[0] + return None + + +@lru_cache(maxsize=64) +def _calendar_name_regex( + locale: str, + kind: Literal['days', 'months'], + attached_before: bool, + attached_after: bool, +) -> tuple[re.Pattern[str], list[int]]: + """Build a regex that matches the wide and abbreviated names of all contexts. + + Each name is a group of its own; the returned list maps ``lastindex - 1`` + back to the day or month. Longer names come first, so they win. + """ + names = {} + data = getattr(Locale.parse(locale), kind) + for context in ('format', 'stand-alone'): + for width in ('wide', 'abbreviated'): + for key, name in data[context][width].items(): + if name: + names.setdefault(name, key) + before = '' if attached_before else r'(?>> parse_date('01.04.04', locale='de_DE', format='short') datetime.date(2004, 4, 1) + If the format spells out the month, month names are recognized, in the + locale and in English: + + >>> parse_date('Apr 1, 2004', locale='en_US') + datetime.date(2004, 4, 1) + >>> parse_date('1. April 2004', locale='de_DE', format='long') + datetime.date(2004, 4, 1) + Two-digit years are placed within 80 years before and 20 years after the current year. @@ -1449,18 +1535,35 @@ def parse_date( month_idx = format_str.index('l') day_idx = format_str.index('d') - indexes = sorted([(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')]) - indexes = {item[1]: idx for idx, item in enumerate(indexes)} + # Patterns like "MMM d, y" spell the month out, so look for a month name + # (in the locale or in English) instead of a number. + month = None + if 'MMM' in fmt.pattern or 'LLL' in fmt.pattern: + month_match = _find_month_name(string, locale, fmt.pattern) + if month_match: + month, start, end = month_match + # Month names can contain digits (e.g. in Tibetan), so drop the + # name before collecting the numbers for the year and the day. + numbers = re.findall(r'(\d+)', string[:start] + ' ' + string[end:]) + + if month is None: + fields = [(year_idx, 'Y'), (month_idx, 'M'), (day_idx, 'D')] + else: + fields = [(year_idx, 'Y'), (day_idx, 'D')] + indexes = {item[1]: idx for idx, item in enumerate(sorted(fields))} - # FIXME: this currently only supports numbers, but should also support month - # names, both in the requested locale, and english + if len(numbers) < len(indexes): + raise ParseError( + f"'{string}' does not represent a valid date for format '{fmt.pattern}'", + ) year = numbers[indexes['Y']] year = _expand_two_digit_year(int(year)) if len(year) == 2 else int(year) - month = int(numbers[indexes['M']]) day = int(numbers[indexes['D']]) - if month > 12: - month, day = day, month + if month is None: + month = int(numbers[indexes['M']]) + if month > 12: + month, day = day, month try: return datetime.date(year, month, day) except ValueError as e: diff --git a/tests/test_dates.py b/tests/test_dates.py index 76a002bc3..bbf68b46d 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -814,6 +814,47 @@ def test_parse_date_out_of_range(): assert isinstance(excinfo.value.__cause__, ValueError) +@pytest.mark.parametrize(('string', 'locale', 'format', 'expected'), [ + # The default (medium) formats of these locales spell out the month. + ('Nov 24, 2026', 'en_US', 'medium', date(2026, 11, 24)), + ('November 24, 2026', 'en_US', 'long', date(2026, 11, 24)), + ('Tuesday, November 24, 2026', 'en_US', 'full', date(2026, 11, 24)), + ('24 Kas 2026', 'tr_TR', 'medium', date(2026, 11, 24)), + ('24 KASIM 2026', 'tr_TR', 'long', date(2026, 11, 24)), + ('24 нояб. 2026 г.', 'ru_RU', 'medium', date(2026, 11, 24)), + ('2026. nov. 24.', 'hu_HU', 'medium', date(2026, 11, 24)), + # English month names are accepted for any locale. + ('24 November 2026', 'de_DE', 'long', date(2026, 11, 24)), + ('24-Nov-2026', 'de_DE', 'long', date(2026, 11, 24)), + # "March" must not be read as "Mar", and "martes" (Tuesday) not as "mar". + ('martes, 10 de marzo de 2026', 'es_ES', 'full', date(2026, 3, 10)), + # In Welsh, "Mawrth" is both Tuesday and March. + ('Dydd Mawrth, 1 Medi 2026', 'cy', 'full', date(2026, 9, 1)), + # Letters the pattern attaches to the month ("d בMMM y", "MMMM'ren'"). + ('9 במרץ 2026', 'he_IL', 'medium', date(2026, 3, 9)), + ('2026(e)ko azaroaren 24(a)', 'eu_ES', 'long', date(2026, 11, 24)), + # Month names that end in a digit must not match a longer number. + ('2026 ལོའི་ཟླ་༡༡ཚེས་24', 'bo', 'medium', date(2026, 11, 24)), +]) +def test_parse_date_month_names(string, locale, format, expected): + assert dates.parse_date(string, locale=locale, format=format) == expected + + +@pytest.mark.parametrize('locale', ['en_US', 'de_DE', 'tr_TR', 'ru_RU', 'fr_FR', 'he_IL', 'ja_JP']) +@pytest.mark.parametrize('format', ['short', 'medium', 'long', 'full']) +def test_parse_date_round_trip(locale, format): + for day in (date(2026, 1, 5), date(2026, 3, 9), date(2026, 11, 24), date(2026, 12, 31)): + formatted = dates.format_date(day, format, locale=locale) + assert dates.parse_date(formatted, locale=locale, format=format) == day + + +@pytest.mark.parametrize('string', ['Nov 2026', '2026', 'Summary 3 2026']) +def test_parse_date_missing_fields(string): + # Used to leak an IndexError, or to read "Mar" out of "Summary". + with pytest.raises(dates.ParseError, match='does not represent a valid date'): + dates.parse_date(string, locale='en_US', format='medium') + + def test_parse_time_out_of_range(): with pytest.raises(dates.ParseError) as excinfo: dates.parse_time('25:00', format='HH:mm')