jcrist · GitHub

This adds support for decoding float/int/numeric-strings into datetime objects when strict=False. These inputs are interpreted as epoch timestamps (seconds since the epoch, UTC), and are decoded as timezone-aware with a UTC timezone.

In [1]: import msgspec
In [2]: import datetime
In [3]: dt = datetime.datetime.now()
In [4]: ts = dt.timestamp()
In [5]:
Out[5]: 1687578573.501321
In [6]: msgspec.convert(ts, type=datetime.datetime)  # by default not supported
---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
Cell In[6], line 1
----> 1 msgspec.convert(ts, type=datetime.datetime)
ValidationError: Expected `datetime`, got `float`
In [7]: msgspec.convert(ts, type=datetime.datetime, strict=False)  # works with strict=False
Out[7]: datetime.datetime(2023, 6, 24, 3, 49, 33, 501321, tzinfo=datetime.timezone.utc)
In [8]: msgspec.convert(str(ts), type=datetime.datetime, strict=False)  # numeric strings work
   ...:  too
Out[8]: datetime.datetime(2023, 6, 24, 3, 49, 33, 501321, tzinfo=datetime.timezone.utc)
In [9]: js = msgspec.json.encode(ts)
In [10]: msgspec.json.decode(js, type=datetime.datetime, strict=False)  # also works with othe
    ...: r protocols
Out[10]: datetime.datetime(2023, 6, 24, 3, 49, 33, 501321, tzinfo=datetime.timezone.utc)

Read the original on github.com ↗