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