Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed deserialization of datetime.date fields #1914

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It took me a while to understand that this wasn't time.time() but converting to a datetime at midnight.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had a passing thought that datetime.time() might be confused with time.time() as well. Maybe I should namespace it here.



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
Loading