From 3518c46d912da7047b9563c58d391b3b236d8ba9 Mon Sep 17 00:00:00 2001 From: Michael Overmeyer Date: Sun, 10 Nov 2024 17:06:28 -0500 Subject: [PATCH] Provide better error messages for BCE-year datetimes. --- CHANGELOG.md | 1 + module.c | 8 ++++++++ tests/tests.py | 11 +++++++++++ 3 files changed, 20 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a111056..c34643a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ * Add support for aarch64 wheels. Thank you @bbayles! * Add wheels for PyPy 3.10 * Added Python 3.13 support +* Better error message when attempting to parse a BCE year (#156). Thanks @javiabellan # 2.x.x diff --git a/module.c b/module.c index 1cf9468..86d0828 100644 --- a/module.c +++ b/module.c @@ -124,6 +124,14 @@ format_unexpected_character_exception(char *field_name, const char *c, field_name, expected_character_count, (expected_character_count != 1) ? "s" : ""); } + else if (*c == '-' && index == 0 && strcmp(field_name, "year") == 0) { + PyErr_Format( + PyExc_ValueError, + "Invalid character while parsing %s ('-', Index: 0). " + "While valid ISO 8601 years, BCE years are not supported by " + "Python's `datetime` objects.", + field_name); + } else { #if PY_VERSION_AT_LEAST_33 PyObject *unicode_str = PyUnicode_FromString(c); diff --git a/tests/tests.py b/tests/tests.py index 15db73c..4955b3a 100644 --- a/tests/tests.py +++ b/tests/tests.py @@ -446,6 +446,17 @@ def test_mixed_basic_and_extended_formats(self): "20140102T01:02:03", ) + def test_bce_years(self): + """ + These are technically valid ISO 8601 datetimes. + However, cPython cannot support values non-positive year values + """ + self.assertRaisesRegex( + ValueError, + r"Invalid character while parsing year \('-', Index: 0\). While valid ISO 8601 years, BCE years are not supported by Python's `datetime` objects.", + parse_datetime, + "-2014-01-02", + ) class Rfc3339TestCase(unittest.TestCase): def test_valid_rfc3339_timestamps(self):