Short way to serialize datetime with marshmallow

Viewed 21591

Here is my situation: I store some datetime in MSSQL, which i get in my python application via SQLAlchemy, and then serialize it thru Marshmallow like this:

class MyVisitSchema(Schema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta:
        additional = ('duration',)
        ordered = True

But here the problem: after serialization i get something like "started_at": "1994-05-20T00:00:00+00:00" which says that UTC+0, but i store all my dates in DB without any timezone info, but in UTC+3.

I know that i can use fields.Method() to change output timezone, but it looks inconvenient. Any ideas how to make my serializer work as it should?)

3 Answers

If it does not work, use the keyword format

started_at = fields.DateTime(format='%Y-%m-%dT%H:%M:%S+03:00')

I would rather use datetimeformat, see: https://marshmallow.readthedocs.io/en/3.0/api_reference.html

Example:

class MyVisitSchema(Schema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta:
        additional = ('duration',)
        ordered = True
        # dateformat = '%Y-%m-%dT%H:%M:%S%z'
        dateformat = '%Y-%m-%dT%H:%M:%S+03:00'

And I prefer to:

class BaseSchema(Schema):
    class Meta:
        dateformat = '%Y-%m-%dT%H:%M:%S+03:00'


class MyVisitSchema(BaseSchema):
    cafe = fields.Nested(CafeSchema)
    started_at = fields.DateTime()
    ended_at = fields.DateTime()

    class Meta(BaseSchema.Meta):
        additional = ('duration',)
        ordered = True
Related