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

版权声明:本文为博主原创文章,欢迎转载,请注明出处 https://blog.csdn.net/mouday/article/details/91047387

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 报错问题解决

展开阅读全文

没有更多推荐了,返回首页