diff --git a/README.md b/README.md index 58b8f6c..5a30f23 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Type-safe JSON (de)serialization for Python. Compatible with mypy type hints. * Support for types out of the box: * Primitive types: * `str`, `int`, `float`, `bool`, `Decimal`, `None` - * `date` as `"%Y-%m-%d"`, `datetime` as `"%Y-%m-%dT%H:%M:%S%z"`, `time` as `"%H:%M:%S"` + * `date` as `"%Y-%m-%d"`, `datetime` as `"%Y-%m-%dT%H:%M:%S%z"` or `"%Y-%m-%dT%H:%M:%S.%f%z"`, `time` as `"%H:%M:%S"` * `UUID` as `str` in format `"8-4-4-4-12"` * `char` type as `str` of length 1 * `Union[]` and therefore `Optional[]` diff --git a/tests/test_json.py b/tests/test_json.py index db0e2ae..fd162b2 100644 --- a/tests/test_json.py +++ b/tests/test_json.py @@ -78,6 +78,9 @@ def test_date(): def test_datetime(): check_success(datetime, datetime(year=2020, month=1, day=1, hour=17, minute=45, second=55, tzinfo=timezone.utc), '"2020-01-01T17:45:55+00:00"') + check_success(datetime, datetime(year=2022, month=7, day=12, hour=14, minute=43, second=53, microsecond=123456, tzinfo=timezone.utc), '"2022-07-12T14:43:53.123456+00:00"') + with raises(JsonError): + loads(datetime, '"2022-07-12"', case=snakecase) def test_time(): diff --git a/typ/encoding.py b/typ/encoding.py index 48f9c51..ad3242c 100644 --- a/typ/encoding.py +++ b/typ/encoding.py @@ -107,8 +107,13 @@ def decode_datetime(decoder, typ, json_value): if typ != datetime: return Unsupported check_type(str, json_value) - parsed = datetime.strptime(json_value, "%Y-%m-%dT%H:%M:%S%z") - return parsed + for fmt in ["%Y-%m-%dT%H:%M:%S%z", "%Y-%m-%dT%H:%M:%S.%f%z"]: + try: + parsed = datetime.strptime(json_value, fmt) + return parsed + except: + pass + raise JsonError(f"no suitable datetime format found for {json_value}") def encode_time(encoder, typ, value):