msgspec
msgspec copied to clipboard
Custom date time format
Description
Maybe it would be much better, adding custom date time format support to Datetime Constraints according to https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
The way msgspec is designed, serialization information generally lives on the encoder/decoder rather than on the type itself. Encoders (for example) currently have no access to type annotation information - all decisions of how a value is encoded have to do with its concrete type.
One of the final todos before the 1.0 release is to revamp our extension mechanism to make it possible to override how builtin supported types encode/decode. This would let you write something like (names/methods not 100% decided yet):
# Register a hook to override how datetimes are encoded
hooks = msgspec.Hooks()
hooks.register_encoder(datetime.datetime, lambda dt: dt.strftime(...))
# Use that hook when encoding an object
msgspec.json.encode(..., hooks=hooks)
The assumption here is that most applications encode all datetimes the same way, so customizing at the field level shouldn't be necessary to support. Would such a solution fit your needs?
hooks.register_encoder could be the right solution in my opinion here. But, how does hooks.register_decoder work ? especially for a datetime type.
It'd be something like:
# Register a hook to override how datetimes are decoded
hooks.register_decoder(datetime.datetime, lambda s: datetime.datetime.strptime(s, ...))
# Use the hooks when decoding an object
msgspec.json.decode(..., type=your_type, hooks=hooks)
Is this going to allow to specify the Msgpack extension type I want to use for encoding? Specifically, I would like to set all datetimes to be encoded as -1, as described in this link: https://github.com/msgpack/msgpack/blob/master/spec.md#timestamp-extension-type
Yes. We currently only serialize timezone-aware datetimes using the timestamp extension, since that extension represents a fixed point in time. Is there a reason you need to encode naive datetimes this way as well? Could you instead only work with aware datetimes?
encoding tz aware datetimes solves my issue, thanks