Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
jun66j5 opened this issue Jan 25, 2025 · 3 comments

Comments

@jun66j5
Copy link
Contributor

jun66j5 commented Jan 25, 2025

$ /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
@pvanover
Copy link

Hi, this is my first issue could I please be assigned I would love to contribute.

@tomasr8
Copy link
Member

tomasr8 commented Jan 25, 2025

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.

@jun66j5
Copy link
Contributor Author

jun66j5 commented Jan 25, 2025

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)

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

No branches or pull requests

3 participants