Skip to content

Commit

Permalink
Fixed deserialization of datetime.date fields
Browse files Browse the repository at this point in the history
Fixes #1913
  • Loading branch information
miguelgrinberg committed Sep 13, 2024
1 parent 8a72af9 commit 11721b9
Show file tree
Hide file tree
Showing 2 changed files with 19 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
17 changes: 16 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 datetime, date
from typing import cast

import pytest
Expand Down Expand Up @@ -48,6 +48,21 @@ def test_boolean_deserialization() -> None:
assert bf.deserialize(1)


def test_datetime_deserialization() -> None:
f = field.Date()
d = datetime.now()
assert d == 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())

d = datetime.now()
assert d.date() == f._deserialize(d.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 11721b9

Please sign in to comment.