python-dataclasses-serialization icon indicating copy to clipboard operation
python-dataclasses-serialization copied to clipboard

Does it serialize DateTime for both JSON and BSON?

Open patarapolw opened this issue 5 years ago • 1 comments

It would be convenient to be able to do that for PyMongo and Flask jsonify.

patarapolw avatar Aug 01 '19 13:08 patarapolw

For BSON, we serialize datetimes, but JSON doesn't have a canonical way of encoding datetimes, 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.

madman-bob avatar Aug 19 '19 14:08 madman-bob