python-dataclasses-serialization
python-dataclasses-serialization copied to clipboard
Does it serialize DateTime for both JSON and BSON?
It would be convenient to be able to do that for PyMongo and Flask jsonify.
For BSON, we serialize datetime
s, but JSON doesn't have a canonical way of encoding datetime
s, so by default we don't.
However, you can add a custom serialization like so:
JSONSerializer.register(
datetime,
lambda t: t.strftime('%Y-%m-%d'),
lambda cls, t: cls.strptime(t, '%Y-%m-%d')
)
and use whatever format is most convenient for your use-case.
Then you can use BSONSerializer
to interact with PyMongo, and JSONSerializer
to interact with Flask, as desired.