Store datetime.date in the format "yyyy-mm-dd" when using Flask jsonify

For some reason, the function jsonifyconverts mine datetime.dateto what seems like an HTTP date. How to save date in format yyyy-mm-ddwhen using jsonify?

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

As indicated in the comments, use jsonify(str(test_date))returns the desired format. However, consider the following case:

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"}"

In this case, the solution str()does not work.

+6
source share
3 answers

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})
+6
source

datetime.date JSON, . Flask , RFC 1123, HTTP- .

JSON, . JSONEncoder Flask.json_encoder .

from flask import Flask
from flask.json import JSONEncoder

class MyJSONEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, date):
            return o.isoformat()

        return super().default(o)

class MyFlask(Flask):
    json_encoder = MyJSONEncoder

app = MyFlask(__name__)

ISO 8601 . JavaScript Date.parse ( ). , .

, RFC 2822 ISO 8601 ( , ).

, , ( JSON), datetime.date , . ( , , date datetime?)

+3

You can change your application .json_encoderattribute by implementing an option JSONEncoderthat formats dates as you wish.

+1
source

Source: https://habr.com/ru/post/1016833/


All Articles