0

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

Arpith S
  • 111
  • 4
  • 15
  • 1
    Does this answer your question? [specific time format for api documenting using flask restplus](https://stackoverflow.com/questions/46326075/specific-time-format-for-api-documenting-using-flask-restplus) – M-Chen-3 Apr 23 '21 at 15:21

1 Answers1

1

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
}
Evgeny
  • 13
  • 3