Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions babel/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -1330,7 +1330,12 @@ def parse_date(
day = int(numbers[indexes['D']])
if month > 12:
month, day = day, month
return datetime.date(year, month, day)
try:
return datetime.date(year, month, day)
except ValueError as e:
raise ParseError(
f"'{string}' does not represent a valid date for format '{fmt.pattern}'"
) from e


def parse_time(
Expand Down Expand Up @@ -1395,7 +1400,12 @@ def parse_time(
minute = int(numbers[indexes['M']])
if len(numbers) > 2:
second = int(numbers[indexes['S']])
return datetime.time(hour, minute, second)
try:
return datetime.time(hour, minute, second)
except ValueError as e:
raise ParseError(
f"'{string}' does not represent a valid time for format '{fmt.pattern}'"
) from e


class DateTimePattern:
Expand Down
14 changes: 14 additions & 0 deletions tests/test_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,20 @@ def test_parse_errors(case, func):
func(case, locale='en_US')


def test_parse_date_out_of_range():
with pytest.raises(dates.ParseError) as excinfo:
dates.parse_date('2005-02-30', format='yyyy-MM-dd')
assert 'does not represent a valid date' in str(excinfo.value)
assert isinstance(excinfo.value.__cause__, ValueError)


def test_parse_time_out_of_range():
with pytest.raises(dates.ParseError) as excinfo:
dates.parse_time('25:00', format='HH:mm')
assert 'does not represent a valid time' in str(excinfo.value)
assert isinstance(excinfo.value.__cause__, ValueError)


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