由于某种原因,该jsonify函数将my转换datetime.date为似乎是HTTP日期的日期。使用时如何保持日期yyyy-mm- dd格式jsonify?
jsonify
datetime.date
yyyy-mm- dd
test_date = datetime.date(2017, 4, 27) print(test_date) # 2017-04-27 test_date_jsonify = jsonify(test_date) print(test_date_jsonify.get_data(as_text=True)) # Thu, 27 Apr 2017 00:00:00 GMT
如注释中所建议,using jsonify(str(test_date))返回所需的格式。但是,请考虑以下情况:
jsonify(str(test_date))
test_dict = {"name": "name1", "date":datetime.date(2017, 4, 27)} print(test_dict) # {"name": "name1", "date":datetime.date(2017, 4, 27)} test_dict_jsonify = jsonify(test_dict) print(test_dict_jsonify.get_data(as_text=True)) # {"date": "Thu, 27 Apr 2017 00:00:00 GMT", "name": "name1"} test_dict_jsonify = jsonify(str(test_dict)) print(test_dict_jsonify.get_data(as_text=True)) # "{"date": datetime.date(2017, 4, 27), "name": "name1"}"
在这种情况下,该str()解决方案不起作用。
str()
按照以下代码片段,您可以执行以下操作:
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
路线:
import datetime as dt @app.route('/', methods=['GET']) def index(): now = dt.datetime.now() return jsonify({'now': now})