Arpith S
Arpith S

Reputation: 121

Custom date format for flask_restful fields.DateTime for marshal_with

I am using flask_restful's fields and marshal_with to serialize my APIs output data. But I am having problems with my date format.

I am storing the date as an SQLAlchemy DateTime type, for example, my date is stored as 2020-01-01 00:00:00.000000 in the database.

I want the date to be serialized in the format yyyy-mm-dd, for example, 2020-01-01 but when I use fields.DateTime(dt_format='iso8601') from flask_restful I get the serialized output as "date": "2020-01-01T00:00:00".

Below are some code snippets that might help

class Product(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.DateTime)

resource_fields = {
    'id': fields.Integer,
    'date': fields.DateTime(dt_format='iso8601')

class ProductList(Resource):
    @marshal_with(resource_fields)
    def get(self):
        data = Product.query.all()
        return data, 200


api.add_resource(ProductList, "/home")

Serialized output

[
    {
        "id": 1,
        "date": "2020-01-01T00:00:00"
    }
}

How do I make a custom serializer for my date in flask_restful to format it as yyyy-mm-dd without the time? Or at least remove T00:00:00 and present the date as 2020-01-01.

Thank you

Upvotes: 1

Views: 3411

Answers (1)

Evgeny
Evgeny

Reputation: 13

I had the same problem, found answer in existing question: https://stackoverflow.com/a/46655059

This code worked great for me:

from flask_restful import fields

class MyDateFormat(fields.Raw):
    def format(self, value):
        return value.strftime('%Y-%m-%d')

resource_fields = {
    'id': fields.Integer,
    'date': MyDateFormat
}

Upvotes: 1

Related Questions