代码如下
# -*- coding: utf-8 -*- from datetime import datetime, date from flask.json import JSONEncoder class CustomJSONEncoder(JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') else: return JSONEncoder.default(self, obj)
使用
from datetime import datetime from flask import Flask, jsonify app = Flask(__name__) # 替换默认的json编码器 app.json_encoder = CustomJSONEncoder @app.route('/test') def test_world(): time = datetime.now() return jsonify({'time': time})
效果
{ "time": "2020-09-17 16:31:55" }
参考