From de9ce6a01098aed59df26c0301e6e694c8c8a3d3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 13 Sep 2024 12:57:32 +0100 Subject: [PATCH] Fixed deserialization of datetime.date fields (#1914) (#1915) Fixes #1913 (cherry picked from commit 6db7e9de0112ea3f68e2ef5f382cf226baf03f4e) Co-authored-by: Miguel Grinberg --- elasticsearch_dsl/field.py | 3 +++ tests/test_field.py | 20 +++++++++++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/elasticsearch_dsl/field.py b/elasticsearch_dsl/field.py index 26f2336b..d992ecc3 100644 --- a/elasticsearch_dsl/field.py +++ b/elasticsearch_dsl/field.py @@ -315,6 +315,9 @@ def _deserialize(self, data: Any) -> Union[datetime, date]: raise ValidationException( f"Could not parse date from the value ({data!r})", e ) + # we treat the yyyy-MM-dd format as a special case + if hasattr(self, "format") and self.format == "yyyy-MM-dd": + data = data.date() if isinstance(data, datetime): if self._default_timezone and data.tzinfo is None: diff --git a/tests/test_field.py b/tests/test_field.py index ee4ed196..a361e580 100644 --- a/tests/test_field.py +++ b/tests/test_field.py @@ -17,7 +17,7 @@ import base64 import ipaddress -from datetime import datetime +from datetime import date, datetime, time from typing import cast import pytest @@ -48,6 +48,24 @@ def test_boolean_deserialization() -> None: assert bf.deserialize(1) +def test_datetime_deserialization() -> None: + f = field.Date() + dt = datetime.now() + assert dt == f._deserialize(dt.isoformat()) + + d = date.today() + assert datetime.combine(d, time()) == f._deserialize(d.isoformat()) + + +def test_date_deserialization() -> None: + f = field.Date(format="yyyy-MM-dd") + d = date.today() + assert d == f._deserialize(d.isoformat()) + + dt = datetime.now() + assert dt.date() == f._deserialize(dt.isoformat()) + + def test_date_field_can_have_default_tz() -> None: f = field.Date(default_timezone="UTC") now = datetime.now()