Skip to content

Commit

Permalink
Add and emit dates.ParseError
Browse files Browse the repository at this point in the history
  • Loading branch information
akx committed Jan 27, 2022
1 parent 88d4319 commit 226c1c0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
15 changes: 12 additions & 3 deletions babel/dates.py
Expand Up @@ -1138,6 +1138,10 @@ def get_period_id(time, tzinfo=None, type=None, locale=LC_TIME):
return "pm"


class ParseError(ValueError):
pass


def parse_date(string, locale=LC_TIME):
"""Parse a date from a string.
Expand All @@ -1152,6 +1156,10 @@ def parse_date(string, locale=LC_TIME):
:param string: the string containing the date
:param locale: a `Locale` object or a locale identifier
"""
numbers = re.findall(r'(\d+)', string)
if not numbers:
raise ParseError("No numbers were found in input")

# TODO: try ISO format first?
format = get_date_format(locale=locale).pattern.lower()
year_idx = format.index('y')
Expand All @@ -1167,7 +1175,6 @@ def parse_date(string, locale=LC_TIME):
# FIXME: this currently only supports numbers, but should also support month
# names, both in the requested locale, and english

numbers = re.findall(r'(\d+)', string)
year = numbers[indexes['Y']]
if len(year) == 2:
year = 2000 + int(year)
Expand All @@ -1194,6 +1201,10 @@ def parse_time(string, locale=LC_TIME):
:return: the parsed time
:rtype: `time`
"""
numbers = re.findall(r'(\d+)', string)
if not numbers:
raise ParseError("No numbers were found in input")

# TODO: try ISO format first?
format = get_time_format(locale=locale).pattern.lower()
hour_idx = format.index('h')
Expand All @@ -1215,8 +1226,6 @@ def parse_time(string, locale=LC_TIME):
if 'pm' in string.lower():
hour_offset = 12

numbers = re.findall(r'(\d+)', string)

# Parse up to three numbers from the string.
minute = second = 0
hour = int(numbers[indexes['H']]) + hour_offset
Expand Down
7 changes: 7 additions & 0 deletions tests/test_dates.py
Expand Up @@ -798,6 +798,13 @@ def test_parse_time(input, expected):
assert dates.parse_time(input, locale='en_US') == expected


@pytest.mark.parametrize('case', ['', 'a', 'aaa'])
@pytest.mark.parametrize('func', [dates.parse_date, dates.parse_time])
def test_parse_errors(case, func):
with pytest.raises(dates.ParseError):
func(case, locale='en_US')


def test_datetime_format_get_week_number():
format = dates.DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
assert format.get_week_number(6) == 1
Expand Down

0 comments on commit 226c1c0

Please sign in to comment.