From fef6edb6bd0780486431b9d8c8724ebe535705d4 Mon Sep 17 00:00:00 2001 From: dongyikuan919 <18511460392@163.com> Date: Sun, 29 Nov 2026 20:14:07 +0800 Subject: [PATCH] Parse explicit compact dates with fixed-width fields --- babel/dates.py | 42 +++++++++++++++++++++++++++++++++++------- tests/test_dates.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 7 deletions(-) diff --git a/babel/dates.py b/babel/dates.py index fa0d568db..2b3d5bf10 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -1363,6 +1363,21 @@ def _expand_two_digit_year(year: int) -> int: return expanded +def _split_compact_date(digits: str, pattern: str) -> list[str] | None: + fields = re.findall(r'y{4,}|yy|MM|LL|d{2,3}', pattern) + if ( + len(fields) != 3 + or ''.join(fields) != pattern + or {field[0] for field in fields} not in ({'y', 'M', 'd'}, {'y', 'L', 'd'}) + or len(digits) != len(pattern) + ): + return None + + first_end = len(fields[0]) + second_end = first_end + len(fields[1]) + return [digits[:first_end], digits[first_end:second_end], digits[second_end:]] + + def parse_date( string: str, locale: Locale | str | None = None, @@ -1375,6 +1390,12 @@ def parse_date( >>> parse_date('01.04.2004', format='dd.MM.yyyy') datetime.date(2004, 4, 1) + An explicit pattern with fixed-width year, month, and day fields can + also be used without separators. + + >>> parse_date('01042004', format='ddMMyyyy') + datetime.date(2004, 4, 1) + If no format is given, or if it is one of "full", "long", "medium", or "short", the function first tries to interpret the string as ISO-8601 date format and then uses the date format for the locale @@ -1420,10 +1441,15 @@ def parse_date( except ValueError: pass # a locale format might fit better, so let's continue + compact_numbers = None if use_predefined_format: fmt = get_date_format(format=format, locale=locale) else: fmt = parse_pattern(format) + if len(numbers) == 1 and string.strip() == numbers[0]: + compact_numbers = _split_compact_date(numbers[0], fmt.pattern) + if compact_numbers is not None: + numbers = compact_numbers format_str = fmt.pattern.lower() year_idx = format_str.index('y') month_idx = format_str.find('m') @@ -1437,15 +1463,17 @@ def parse_date( # FIXME: this currently only supports numbers, but should also support month # names, both in the requested locale, and english - 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 try: + year_text = numbers[indexes['Y']] + year = ( + _expand_two_digit_year(int(year_text)) if len(year_text) == 2 else int(year_text) + ) + month = int(numbers[indexes['M']]) + day = int(numbers[indexes['D']]) + if month > 12 and compact_numbers is None: + month, day = day, month return datetime.date(year, month, day) - except ValueError as e: + except (IndexError, ValueError) as e: raise ParseError( f"'{string}' does not represent a valid date for format '{fmt.pattern}'", ) from e diff --git a/tests/test_dates.py b/tests/test_dates.py index d9813b8f2..337f34d01 100644 --- a/tests/test_dates.py +++ b/tests/test_dates.py @@ -742,6 +742,42 @@ def test_parse_date_custom_format(): assert dates.parse_date('2024-04-01', format='yyyy.dd.mm') == date(2024, 1, 4) +@pytest.mark.parametrize( + ('pattern', 'value'), + [ + ('ddMMyyyy', date(2004, 4, 1)), + ('yyyyMMdd', date(24, 4, 1)), + ('yyyyLLddd', date(2004, 4, 1)), + ], +) +def test_parse_date_compact_format(pattern, value): + formatted = dates.format_date(value, format=pattern, locale='en_US') + assert dates.parse_date(formatted, format=pattern, locale='en_US') == value + + +def test_parse_date_compact_unicode_digits(): + assert dates.parse_date('٢٠٠٤٠٤٠١', format='yyyyMMdd') == date(2004, 4, 1) + + +def test_parse_date_compact_two_digit_year(): + with freezegun.freeze_time('2090-06-01'): + assert dates.parse_date('100401', format='yyMMdd') == date(2110, 4, 1) + + +@pytest.mark.parametrize( + ('value', 'pattern'), + [ + ('2024041', 'yyyyMMdd'), + ('20243101', 'yyyyMMdd'), + ('20240401', "yyyy'X'MMdd"), + ('202411', 'yyyyMd'), + ], +) +def test_parse_date_invalid_compact_format(value, pattern): + with pytest.raises(dates.ParseError): + dates.parse_date(value, format=pattern) + + @pytest.mark.parametrize( ('input', 'expected'), [