Skip to content

Commit d6d021f

Browse files
committed
Provide better error messages for BCE-year datetimes.
1 parent 40b68f3 commit d6d021f

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
* Add support for aarch64 wheels. Thank you @bbayles!
2626
* Add wheels for PyPy 3.10
2727
* Added Python 3.13 support
28+
* Better error message when attempting to parse a BCE year (#156). Thanks @javiabellan
2829

2930
# 2.x.x
3031

module.c

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,14 @@ format_unexpected_character_exception(char *field_name, const char *c,
124124
field_name, expected_character_count,
125125
(expected_character_count != 1) ? "s" : "");
126126
}
127+
else if (*c == '-' && index == 0 && strcmp(field_name, "year") == 0) {
128+
PyErr_Format(
129+
PyExc_ValueError,
130+
"Invalid character while parsing %s ('-', Index: 0). "
131+
"While valid ISO 8601 years, BCE years are not supported by "
132+
"Python's `datetime` objects.",
133+
field_name);
134+
}
127135
else {
128136
#if PY_VERSION_AT_LEAST_33
129137
PyObject *unicode_str = PyUnicode_FromString(c);

tests/tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,17 @@ def test_mixed_basic_and_extended_formats(self):
446446
"20140102T01:02:03",
447447
)
448448

449+
def test_bce_years(self):
450+
"""
451+
These are technically valid ISO 8601 datetimes.
452+
However, cPython cannot support values non-positive year values
453+
"""
454+
self.assertRaisesRegex(
455+
ValueError,
456+
r"Invalid character while parsing year \('-', Index: 0\). While valid ISO 8601 years, BCE years are not supported by Python's `datetime` objects.",
457+
parse_datetime,
458+
"-2014-01-02",
459+
)
449460

450461
class Rfc3339TestCase(unittest.TestCase):
451462
def test_valid_rfc3339_timestamps(self):

0 commit comments

Comments
 (0)