Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 35 additions & 7 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -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')
Expand All @@ -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
Expand Down
36 changes: 36 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
[
Expand Down