天天看點

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

json序列化時間對象的時候報錯:

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

解決辦法

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

參考:

python datetime.datetime is not JSON serializable 報錯問題解決