Skip to content

Add handling for datetimes to the default Json Converter #872

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

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
14 changes: 13 additions & 1 deletion temporalio/converter.py
Copy link
Member

Choose a reason for hiding this comment

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

I think we also have to update the README that we support datetime now. I do wonder whether we want to support date and time, but maybe not.

Original file line number Diff line number Diff line change
Expand Up @@ -500,6 +500,9 @@ def default(self, o: Any) -> Any:

See :py:meth:`json.JSONEncoder.default`.
"""
# Datetime support
if isinstance(o, datetime):
return o.isoformat()
# Dataclass support
if dataclasses.is_dataclass(o):
return dataclasses.asdict(o)
Expand Down Expand Up @@ -1132,7 +1135,7 @@ async def decode_failure(
BinaryPlainPayloadConverter(),
JSONProtoPayloadConverter(),
BinaryProtoPayloadConverter(),
JSONPlainPayloadConverter(),
JSONPlainPayloadConverter(), # JSON Plain needs to remain in last because it throws on unknown types
)

DataConverter.default = DataConverter()
Expand Down Expand Up @@ -1399,6 +1402,15 @@ def value_to_type(
# Any or primitives
if hint is Any:
return value
elif hint is datetime:
if isinstance(value, str):
try:
return _get_iso_datetime_parser()(value)
except ValueError as err:
raise TypeError(f"Failed parsing datetime string: {value}") from err
elif isinstance(value, datetime):
return value
raise TypeError(f"Expected datetime or ISO8601 string, got {type(value)}")
elif hint is int or hint is float:
if not isinstance(value, (int, float)):
raise TypeError(f"Expected value to be int|float, was {type(value)}")
Expand Down
39 changes: 38 additions & 1 deletion tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import traceback
from collections import deque
from dataclasses import dataclass
from datetime import datetime, timezone
from datetime import datetime, timezone, timedelta
from enum import Enum, IntEnum
from typing import (
Any,
Expand Down Expand Up @@ -86,6 +86,11 @@ class MyDataClass:
baz: SerializableEnum


@dataclass
class DatetimeClass:
datetime: datetime


async def test_converter_default():
async def assert_payload(
input,
Expand Down Expand Up @@ -178,6 +183,38 @@ async def assert_payload(
type_hint=RawValue,
)

# Without type hint, it is deserialized as a str
await assert_payload(
datetime(2020, 1, 1, 1, 1, 1),
"json/plain",
'"2020-01-01T01:01:01"',
expected_decoded_input="2020-01-01T01:01:01",
)

# With type hint, it is deserialized as a datetime
await assert_payload(
datetime(2020, 1, 1, 1, 1, 1, 1),
"json/plain",
'"2020-01-01T01:01:01.000001"',
type_hint=datetime,
)

# Timezones work
await assert_payload(
datetime(2020, 1, 1, 1, 1, 1, tzinfo=timezone(timedelta(hours=5))),
"json/plain",
'"2020-01-01T01:01:01+05:00"',
type_hint=datetime,
)

# Data class with datetime
await assert_payload(
DatetimeClass(datetime=datetime(2020, 1, 1, 1, 1, 1)),
"json/plain",
'{"datetime":"2020-01-01T01:01:01"}',
type_hint=DatetimeClass,
)


def test_binary_proto():
# We have to test this separately because by default it never encodes
Expand Down
Loading