Skip to content

Commit

Permalink
Fixed deserialization of datetime.date fields
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Sep 13, 2024
1 parent 8a72af9 commit 6444c80
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 3 additions & 0 deletions elasticsearch_dsl/field.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
20 changes: 19 additions & 1 deletion tests/test_field.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

import base64
import ipaddress
from datetime import datetime
from datetime import date, datetime, time
from typing import cast

import pytest
Expand Down Expand Up @@ -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()
Expand Down

0 comments on commit 6444c80

Please sign in to comment.