使用棉花糖序列化日期时间的简短方法

Ale*_*nko 7 python sql-server serialization sqlalchemy marshmallow

这是我的情况:我在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
Run Code Online (Sandbox Code Playgroud)

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

我知道我可以fields.Method()用来改变输出时区,但看起来不方便.任何想法如何使我的序列化工作正常工作?)

小智 8

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

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


Ale*_*nko 6

在官方纪录片中找到一些信息.所以,我的问题可以用

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

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


Wak*_*eng 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'
Run Code Online (Sandbox Code Playgroud)

我更喜欢:

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
Run Code Online (Sandbox Code Playgroud)

  • `Meta.dateformat` 已重命名为 `Meta.datetimeformat`;请参阅[升级文档](https://marshmallow.readthedocs.io/en/latest/upgrading.html#datetime-field-dateformat-meta-option-is-renamed-datetimeformat)以供参考。 (3认同)