TypeError: Object of type 'datetime' is not JSON serializable

Disclaimer: This article is a blogger original article, welcome to reprint, please indicate the source https://blog.csdn.net/mouday/article/details/91047387

json object serialization time when the error:

    TypeError: Object of type 'datetime' is not JSON serializable

Solution

Rewriting sequence class json

# -*- coding: utf-8 -*-

import json

import datetime


class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')

        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")

        else:
            return json.JSONEncoder.default(self, obj)


if __name__ == '__main__':
    data = {"name": "Tom", "birthday": datetime.datetime.now()}
    print(json.dumps(data, cls=DateEncoder))
    # {"name": "Tom", "birthday": "2019-06-06 17:24:19"}

Reference:
Python datetime.datetime IS not solve the problem of error JSON Serializable

Guess you like

Origin blog.csdn.net/mouday/article/details/91047387