Skip to content

Fix parse_date and parse_time to raise ParseError instead of ValueError#1282

Open
gaoflow wants to merge 1 commit into
python-babel:masterfrom
gaoflow:fix-parse-date-time-value-error
Open

Fix parse_date and parse_time to raise ParseError instead of ValueError#1282
gaoflow wants to merge 1 commit into
python-babel:masterfrom
gaoflow:fix-parse-date-time-value-error

Conversation

@gaoflow

@gaoflow gaoflow commented Jun 24, 2026

Copy link
Copy Markdown

Problem

parse_date and parse_time both catch ParseError as their documented error type, but when the parsed numbers produce an out-of-range date or time value, the internal datetime.date / datetime.time constructor raises a raw ValueError that escapes to the caller uncaught.

Reported in #1178. Example:

>>> from babel.dates import parse_date
>>> parse_date('2005-12-31T01:02:03Z')
# Before: ValueError: day is out of range for month
# After: ParseError: String '2005-12-31T01:02:03Z' does not match format 'MMM d, y' (day is out of range for month)
>>> from babel.dates import parse_time
>>> parse_time('25:00')
# Before: ValueError: hour must be in 0..23
# After: ParseError: String '25:00' does not match format 'h:mm:ss a' (hour must be in 0..23)

Fix

Wrap the final datetime.date(year, month, day) call in parse_date and datetime.time(hour, minute, second) call in parse_time with try/except ValueError, re-raising as ParseError with an informative message that includes the input string and the expected format pattern.

All 2245 existing tests pass (2 xfailed unchanged).

Fixes #1178.

When parse_date or parse_time receives an input string whose numbers
produce an out-of-range date or time (e.g. month 13, hour 25), the
final datetime.date / datetime.time constructor raises a raw ValueError.
Callers that catch ParseError (the documented error type for this module)
never see the exception.

Wrap both constructors in try/except and re-raise as ParseError with a
message that includes the input string and the expected format pattern.

Fixes python-babel#1178.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

parse_date raises ValueError: day is out of range for month for iso8601 string

1 participant