Keep a datetime.date in 'yyyy-mm-dd' format when using Flask's jsonify Keep a datetime.date in 'yyyy-mm-dd' format when using Flask's jsonify flask flask

Keep a datetime.date in 'yyyy-mm-dd' format when using Flask's jsonify


Following this snippet you can do this:

from flask.json import JSONEncoderfrom datetime import dateclass CustomJSONEncoder(JSONEncoder):    def default(self, obj):        try:            if isinstance(obj, date):                return obj.isoformat()            iterable = iter(obj)        except TypeError:            pass        else:            return list(iterable)        return JSONEncoder.default(self, obj)app = Flask(__name__)app.json_encoder = CustomJSONEncoder

Route:

import datetime as dt@app.route('/', methods=['GET'])def index():    now = dt.datetime.now()    return jsonify({'now': now})


datetime.date is not a JSON type, so it's not serializable by default. Instead, Flask adds a hook to dump the date to a string in RFC 1123 format, which is consistent with dates in other parts of HTTP requests and responses.

Use a custom JSON encoder if you want to change the format. Subclass JSONEncoder and set Flask.json_encoder to it.

from flask import Flaskfrom flask.json import JSONEncoderclass MyJSONEncoder(JSONEncoder):    def default(self, o):        if isinstance(o, date):            return o.isoformat()        return super().default(o)class MyFlask(Flask):    json_encoder = MyJSONEncoderapp = MyFlask(__name__)

It is a good idea to use ISO 8601 to transmit and store the value. It can be parsed unambiguously by JavaScript Date.parse (and other parsers). Choose the output format when you output, not when you store.

A string representing an RFC 2822 or ISO 8601 date (other formats may be used, but results may be unexpected).

When you load the data, there's no way to know the value was meant to be a date instead of a string (since date is not a JSON type), so you don't get a datetime.date back, you get a string. (And if you did get a date, how would it know to return date instead of datetime?)


You can change your app's .json_encoder attribute, implementing a variant of JSONEncoder that formats dates as you see fit.