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

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

            </div>
目录
相关文章
|
4月前
|
JSON 数据格式 Python
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
TypeError the JSON object must be str, bytes or bytearray, not ‘list‘
|
9月前
|
JSON 数据格式
TypeError: Object of type ‘float32‘ is not JSON serializable
TypeError: Object of type ‘float32‘ is not JSON serializable
130 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
142 0
|
NoSQL Redis
Redis序列化的问题:Failed to deserialize object type
您好,我是码农飞哥,感谢您阅读本文!最近在进行框架改造,历史遗留代码对Redis的使用不当,导致了一些问题。
268 0
Redis序列化的问题:Failed to deserialize object type
|
JSON 数据格式 Python
pymongo:Object of type ObjectId is not JSON serializable
1.问题原因 是由于ObjectId无法在服务端生成json数据 请在文件头引入这两个python包
215 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
77 0
|
JSON 数据格式 Python
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
72 0
PHP:Cannot use object of type stdClass as array
PHP:Cannot use object of type stdClass as array
152 0
|
JSON 数据格式
TypeError: Object of type 'datetime' is not JSON serializable
TypeError: Object of type 'datetime' is not JSON serializable
|
1月前
|
JSON 前端开发 Java
Json格式数据解析
Json格式数据解析