Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short way to serialize datetime with marshmallow

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

like image 333
Alexey Lysenko Avatar asked Mar 04 '16 12:03

Alexey Lysenko


People also ask

What is marshmallow serialization?

Introduction. Marshmallow, stylized as “marshmallow”, is an object-relational mapping library which is used to convert objects to and from Python data types. It is often used alongside SQLAlchemy, an ORM that maps database schemas to Python objects.

What is serialization and Deserialization in marshmallow?

Deserialization is the opposite of serialization. To serialize, we converted data from Python to JSON. To deserialize, we are converting JSON data to SQLAlchemy objects. When deserializing objects from the SQLite database, Marshmallow automatically converts the serialized data to a Python object.

Is marshmallow an ORM?

marshmallow is an ORM/ODM/framework-agnostic library for converting complex datatypes, such as objects, to and from native Python datatypes. In short, marshmallow schemas can be used to: Validate input data. Deserialize input data to app-level objects.


1 Answers

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

like image 78
Alexey Lysenko Avatar answered Sep 23 '22 10:09

Alexey Lysenko