Skip to content

Commit 335884a

Browse files
committed
Add and emit dates.ParseError
1 parent 7aee5b8 commit 335884a

2 files changed

Lines changed: 19 additions & 3 deletions

File tree

babel/dates.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1138,6 +1138,10 @@ def get_period_id(time, tzinfo=None, type=None, locale=LC_TIME):
11381138
return "pm"
11391139

11401140

1141+
class ParseError(ValueError):
1142+
pass
1143+
1144+
11411145
def parse_date(string, locale=LC_TIME):
11421146
"""Parse a date from a string.
11431147
@@ -1152,6 +1156,10 @@ def parse_date(string, locale=LC_TIME):
11521156
:param string: the string containing the date
11531157
:param locale: a `Locale` object or a locale identifier
11541158
"""
1159+
numbers = re.findall(r'(\d+)', string)
1160+
if not numbers:
1161+
raise ParseError("No numbers were found in input")
1162+
11551163
# TODO: try ISO format first?
11561164
format = get_date_format(locale=locale).pattern.lower()
11571165
year_idx = format.index('y')
@@ -1167,7 +1175,6 @@ def parse_date(string, locale=LC_TIME):
11671175
# FIXME: this currently only supports numbers, but should also support month
11681176
# names, both in the requested locale, and english
11691177

1170-
numbers = re.findall(r'(\d+)', string)
11711178
year = numbers[indexes['Y']]
11721179
if len(year) == 2:
11731180
year = 2000 + int(year)
@@ -1194,6 +1201,10 @@ def parse_time(string, locale=LC_TIME):
11941201
:return: the parsed time
11951202
:rtype: `time`
11961203
"""
1204+
numbers = re.findall(r'(\d+)', string)
1205+
if not numbers:
1206+
raise ParseError("No numbers were found in input")
1207+
11971208
# TODO: try ISO format first?
11981209
format = get_time_format(locale=locale).pattern.lower()
11991210
hour_idx = format.index('h')
@@ -1215,8 +1226,6 @@ def parse_time(string, locale=LC_TIME):
12151226
if 'pm' in string.lower():
12161227
hour_offset = 12
12171228

1218-
numbers = re.findall(r'(\d+)', string)
1219-
12201229
# Parse up to three numbers from the string.
12211230
minute = second = 0
12221231
hour = int(numbers[indexes['H']]) + hour_offset

tests/test_dates.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -800,6 +800,13 @@ def test_parse_time(input, expected):
800800
assert dates.parse_time(input, locale='en_US') == expected
801801

802802

803+
@pytest.mark.parametrize('case', ['', 'a', 'aaa'])
804+
@pytest.mark.parametrize('func', [dates.parse_date, dates.parse_time])
805+
def test_parse_errors(case, func):
806+
with pytest.raises(dates.ParseError):
807+
func(case, locale='en_US')
808+
809+
803810
def test_datetime_format_get_week_number():
804811
format = dates.DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
805812
assert format.get_week_number(6) == 1

0 commit comments

Comments
 (0)