diff options
author | Eric L <ewl+git@lavar.de> | 2022-02-20 10:35:01 +0100 |
---|---|---|
committer | Aarni Koskela <akx@iki.fi> | 2022-10-31 19:30:05 +0200 |
commit | a946ae6bad2701a021969d82b550ba6be1f5c7d7 (patch) | |
tree | 223d946114f7af74367c131d3bada3e0efef98ea /babel | |
parent | 05df10fd1474e929793183c3b0ffa28251df79eb (diff) | |
download | babel-a946ae6bad2701a021969d82b550ba6be1f5c7d7.tar.gz |
Adapt parse_date to handle ISO dates in ASCII format
Diffstat (limited to 'babel')
-rw-r--r-- | babel/dates.py | 20 |
1 files changed, 17 insertions, 3 deletions
diff --git a/babel/dates.py b/babel/dates.py index a30cac9..8228bef 100644 --- a/babel/dates.py +++ b/babel/dates.py @@ -1179,13 +1179,18 @@ 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) >>> parse_date('01.04.2004', locale='de_DE') datetime.date(2004, 4, 1) + >>> parse_date('2004-04-01', locale='en_US') + datetime.date(2004, 4, 1) + >>> parse_date('2004-04-01', locale='de_DE') + datetime.date(2004, 4, 1) :param string: the string containing the date :param locale: a `Locale` object or a locale identifier @@ -1195,7 +1200,16 @@ def parse_date(string, locale=LC_TIME, format='medium'): if not numbers: raise ParseError("No numbers were found in input") - # TODO: try ISO format first? + # 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, flags=re.ASCII) # allow only ASCII digits + 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') month_idx = format_str.index('m') |