diff --git a/sharedmodels/sharedmodels/dataclassbase.py b/sharedmodels/sharedmodels/dataclassbase.py index cb8626f82..5e2923631 100644 --- a/sharedmodels/sharedmodels/dataclassbase.py +++ b/sharedmodels/sharedmodels/dataclassbase.py @@ -196,9 +196,11 @@ def _get_value_for_typed_field( return typing_hint(val) # type: ignore except: ... - elif isinstance(val, str) and issubclass(typing_hint, datetime.datetime): + elif isinstance(val, str) and issubclass(typing_hint, datetime.date): # ISO-8601 conversion. - return datetime.datetime.fromisoformat(val) + if issubclass(typing_hint, datetime.datetime): + return datetime.datetime.fromisoformat(val) + return datetime.date.fromisoformat(val) raise DataClassFromDictValueError( f"Could not match {val} with static type {typing_hint}" @@ -301,7 +303,7 @@ def replace_with_json_serialisable_types(val: Any) -> Any: Its inverse is :func:`replace_serialised_types_with_builtin_types`. """ - if isinstance(val, datetime.datetime): + if isinstance(val, datetime.date): return val.isoformat() elif isinstance(val, dict): return dict( diff --git a/sharedmodels/sharedmodels/tests/unit/test_dataclassbase.py b/sharedmodels/sharedmodels/tests/unit/test_dataclassbase.py index 2b964a2d8..367e66800 100644 --- a/sharedmodels/sharedmodels/tests/unit/test_dataclassbase.py +++ b/sharedmodels/sharedmodels/tests/unit/test_dataclassbase.py @@ -340,6 +340,19 @@ class A(DataClassBase): assert reinflated_a.some_datetime == dt +def test_date_json_serialisation(): + @dataclass + class A(DataClassBase): + some_datetime: datetime.date + + date = datetime.date.today() + + a = A(date) + reinflated_a = a.from_json(a.as_json()) + assert isinstance(reinflated_a, A) + assert reinflated_a.some_datetime == date + + def test_override_values(): @dataclass class A(DataClassBase):