3

Default, DateTime fields will be serialized to a format like 2020-02-02T13:25:33, but I want to serialized it to unix timestamp. I've read flask-marshmallow documents and marshmallow documents, I only find ways to custom the output datetime format. So my question is that any simple solution can I do to achieve that?

I have a model definition:

class Folder(CRUDMixin, db.Model):
    __tablename__ = 'folder'
    create_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    update_time = db.Column(db.DateTime, index=True, default=datetime.utcnow)

And it's schema definition:

class FolderSchema(marshmallow.Schema):
    create_time = DateTime(format='timestamp')
    update_time = DateTime(format='timestamp')

I have found a quite complex way to achieve that, I'm trying to find another simple way.

class DateTime(fields.DateTime):
    """
    Class extends marshmallow standard DateTime with "timestamp" format.
    """

    SERIALIZATION_FUNCS = \
        fields.DateTime.SERIALIZATION_FUNCS.copy()
    DESERIALIZATION_FUNCS = \
        fields.DateTime.DESERIALIZATION_FUNCS.copy()

    SERIALIZATION_FUNCS['timestamp'] = lambda x: int(x.timestamp()) * 1000
    DESERIALIZATION_FUNCS['timestamp'] = datetime.fromtimestamp


class FolderSchema(marshmallow.Schema):
    create_time = DateTime(format='timestamp')
    update_time = DateTime(format='timestamp')
Jérôme
  • 13,328
  • 7
  • 56
  • 106
einverne
  • 6,454
  • 6
  • 45
  • 91

1 Answers1

2

The way you're doing it makes sense.

You could money-patch DateTime rather than overriding it to simplify the imports throughout your application. Just modify fields.DateTime.SERIALIZATION_FUNCS and fields.DateTime.DESERIALIZATION_FUNCS and you're done.

Serialization to/from timestamp is an old TODO but we're not done with it yet:

Jérôme
  • 13,328
  • 7
  • 56
  • 106