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

Datetime without timezone are decoded as str with msgspec.msgpack. in 0.18.6 #658

Closed
sihrc opened this issue Mar 14, 2024 · 1 comment
Closed

Comments

@sihrc
Copy link

sihrc commented Mar 14, 2024

Description

import datetime

import msgspec
import pytz

print(type(msgspec.msgpack.decode(msgspec.msgpack.encode(datetime.datetime.now()))))
# <class 'str'>

print(
    type(
        msgspec.msgpack.decode(
            msgspec.msgpack.encode(datetime.datetime.now(tz=pytz.UTC))
        )
    )
)
# <class 'datetime.datetime'>

python==3.11.0rc1
msgspec==0.18.6

Maybe related to #534 ?

@jcrist
Copy link
Owner

jcrist commented Mar 14, 2024

Datetimes without timezones encode as strings, since the msgpack timestamp extension only represents datetimes with timezones.

When decoding, the decoder has no way to know that the value should be interpreted as a datetime rather than a string unless you provide it a type annotation representing the expected schema.

In [1]: import datetime

In [2]: import msgspec

In [3]: dt = datetime.datetime.now()

In [4]: encoded = msgspec.msgpack.encode(dt)

In [5]: msgspec.msgpack.decode(encoded)  # no type annotation
Out[5]: '2024-03-14T13:28:46.058671'

In [6]: msgspec.msgpack.decode(encoded, type=datetime.datetime)  # with type annotation
Out[6]: datetime.datetime(2024, 3, 14, 13, 28, 46, 58671)

See the docs for more information.

@jcrist jcrist closed this as completed Mar 14, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants