12

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?)

Alexey Lysenko
  • 1,890
  • 2
  • 12
  • 28

3 Answers3

16

Found some info in official documentaries. So, my issue can be solved using

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

hardcode a bit, but looks better than using additional function with fields.Method()

Alexey Lysenko
  • 1,890
  • 2
  • 12
  • 28
8

If it does not work, use the keyword format

started_at = fields.DateTime(format='%Y-%m-%dT%H:%M:%S+03:00')
Zoe
  • 27,060
  • 21
  • 118
  • 148
5

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
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30
  • I had to explicitly use the `DateTime(format='...')` syntax instead of the `Meta.dateformat` one for the release 3.0.0rc5. Did work before though. – cr0 May 31 '19 at 11:00
  • 4
    `Meta.dateformat` has been renamed to `Meta.datetimeformat`; see the [upgrade docs](https://marshmallow.readthedocs.io/en/latest/upgrading.html#datetime-field-dateformat-meta-option-is-renamed-datetimeformat) for reference. – GergelyPolonkai Aug 29 '19 at 07:43