Skip to content

Commit

Permalink
Provide better error messages for BCE-year datetimes.
Browse files Browse the repository at this point in the history
  • Loading branch information
movermeyer committed Nov 10, 2024
1 parent 08f4a50 commit ba2325c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 8 additions & 0 deletions module.c
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
11 changes: 11 additions & 0 deletions tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down

0 comments on commit ba2325c

Please sign in to comment.