11

这是我的情况:我在 MSSQL 中存储了一些日期时间,我通过 SQLAlchemy 在我的 python 应用程序中获取了这些日期时间,然后通过 Marshmallow 将其序列化,如下所示:

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

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

但是这里的问题是:在序列化之后,我得到类似"started_at": "1994-05-20T00:00:00+00:00"UTC+0 的信息,但是我将所有日期都存储在 DB 中,没有任何时区信息,而是在 UTC+3 中。

我知道我可以fields.Method()用来更改输出时区,但它看起来不方便。有什么想法可以让我的序列化程序正常工作吗?)

4

3 回答 3

13

在官方纪录片中找到了一些信息。所以,我的问题可以使用解决

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

硬编码一点,但看起来比使用附加功能更好fields.Method()

于 2016-03-04T13:04:52.217 回答
5

我宁愿使用datetimeformat,请参阅:https ://marshmallow.readthedocs.io/en/3.0/api_reference.html

例子:

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'

我更喜欢:

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
于 2019-05-29T08:17:36.783 回答
5

如果不起作用,请使用关键字format

started_at = fields.DateTime(format='%Y-%m-%dT%H:%M:%S+03:00')
于 2019-04-16T09:51:39.553 回答