babel
babel copied to clipboard
parse_date raises `ValueError: day is out of range for month` for iso8601 string
$ /venv/py311/bin/python
Python 3.11.11 (main, Dec 4 2024, 08:55:08) [GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import babel
>>> babel.__version__
'2.16.0'
>>> from datetime import datetime
>>> from babel.dates import format_date
>>> from babel.dates import parse_date
>>> parse_date('2005-12-31T01:02:03Z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/venv/py311/lib/python3.11/site-packages/babel/dates.py", line 1252, in parse_date
return datetime.date(year, month, day)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: day is out of range for month
Hi, this is my first issue could I please be assigned I would love to contribute.
Hi! Go for it :) We'll first need to understand if this is actually a bug though. Have a look at https://github.com/python-babel/babel/blob/master/CONTRIBUTING.md to help you get started.
Ah, I was stupid. But the message "day is out of range for month" confused me.
I'd suggest to add the expected date pattern to the message of the exception.
diff --git a/babel/dates.py b/babel/dates.py
index 8a4932d4b..087d67e2d 100644
--- a/babel/dates.py
+++ b/babel/dates.py
@@ -1295,7 +1295,10 @@ 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"Invalid date string, expected '{fmt.pattern}' ({e})") from None
def parse_time(
After the patch, the following error is raised:
>>> from babel.dates import parse_date
>>> parse_date('2005-12-31T00:00:00Z')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jun66j5/src/babel.git/babel/dates.py", line 1301, in parse_date
raise ParseError(f"Invalid date string, expected '{fmt.pattern}' ({e})") from None
babel.dates.ParseError: Invalid date string, expected 'MMM d, y' (day is out of range for month)