一、前言
当利用models模块从数据库获取数据时,当获的取数据序列化时,如果获取的数据中有关于时间类型的字段,则会报错,错误如下:
TypeError: datetime.datetime(2018, 8, 28, 10, 31, 56, 158078) is not JSON serializable
二、解决方法
import json
from datetime import date, datetime
class MyEncoder(json.JSONEncoder):
def default(self, obj):
# if isinstance(obj, datetime.datetime):
# return int(mktime(obj.timetuple()))
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj)
三、测试
import json
from datetime import date, datetime
data = [
{
'id': 2,
'hostname': 'openstack',
'create_date': datetime(2018, 8, 28, 10, 31, 56, 158078),
'ip': '10.0.0.12',
'mod_date': datetime(2018, 8, 28, 10, 31, 56, 158078),
'detail': '云计算',
'servertype__serverName': 'openstack',
}
] class MyEncoder(json.JSONEncoder):
def default(self, obj):
# if isinstance(obj, datetime.datetime):
# return int(mktime(obj.timetuple()))
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
else:
return json.JSONEncoder.default(self, obj) print(json.dumps(data, cls=MyEncoder))
输出结果:
[
{
"id": 2,
"ip": "10.0.0.12",
"mod_date": "2018-08-28 10:31:56",
"servertype__serverName": "backup",
"hostname": "openstack",
"create_date": "2018-08-28 10:31:56",
"detail": "\u4e91\u8ba1\u7b97"
}
]