Skip to content

Commit

Permalink
Yet another try at ISO-8601
Browse files Browse the repository at this point in the history
Being a bit more strict on the format, it allows us to support also the basic format, without dashes
  • Loading branch information
ericzolf committed Apr 13, 2022
1 parent 86b8f89 commit 1bb624f
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions babel/dates.py
Expand Up @@ -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)
Expand All @@ -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')
Expand Down

0 comments on commit 1bb624f

Please sign in to comment.