From 1bb624f83995978947e90a7037301d35833e39a4 Mon Sep 17 00:00:00 2001 From: Eric L Date: Wed, 13 Apr 2022 07:27:40 +0200 Subject: [PATCH] Yet another try at ISO-8601 Being a bit more strict on the format, it allows us to support also the basic format, without dashes --- babel/dates.py | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/babel/dates.py b/babel/dates.py index 9e8c5179b..1ef12ce33 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -1145,8 +1145,9 @@ class ParseError(ValueError): def parse_date(string, locale=LC_TIME, format='medium'): """Parse a date from a string. - This function uses the date format for the locale as a hint to determine - the order in which the date fields appear in the string. + This function first tries to interpret the string as ISO-8601 + date format, then uses the date format for the locale as a hint to + determine the order in which the date fields appear in the string. >>> parse_date('4/1/04', locale='en_US') datetime.date(2004, 4, 1) @@ -1165,11 +1166,14 @@ def parse_date(string, locale=LC_TIME, format='medium'): if not numbers: raise ParseError("No numbers were found in input") - # we try ISO-alike format first, meaning similar to YYYY-MM-DD - if len(numbers) == 3: - ints = list(map(int, numbers)) - if ints[0] > 31 and ints[1] <= 12 and ints[2] <= 31: - return date(*ints) + # we try ISO-8601 format first, meaning similar to formats + # extended YYYY-MM-DD or basic YYYYMMDD + iso_alike = re.match(r'^(\d{4})-?([01]\d)-?([0-3]\d)$', string) + if iso_alike: + try: + return date(*map(int, iso_alike.groups())) + except ValueError: + pass # a locale format might fit better, so let's continue format_str = get_date_format(format=format, locale=locale).pattern.lower() year_idx = format_str.index('y')