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

前端 未结 3 1250
故里飘歌
故里飘歌 2020-12-05 18:36

For some reason, the jsonify function is converting my datetime.date to what appears to be an HTTP date. How can I keep the date in yyyy-mm-d

3条回答
  •  清歌不尽
    2020-12-05 19:19

    Following this snippet you can do this:

    from flask.json import JSONEncoder
    from datetime import date
    
    
    class 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})
    

提交回复
热议问题