json序列化datetime类型数据
错误描述:
import json
import datetime
a = datetime.datetime.now()
print(a)
b = json.dumps(a)
print(b)
如上代码,执行会报错:
TypeError: datetime.datetime(2017, 2, 5, 10, 27, 48, 155328) is not JSON serializable
因为datetime类型的数据无法直接用json序列化。
解决办法:
class CJsonEncoder(json.JSONEncoder): def default(self, obj): #if isinstance(obj, datetime): #return obj.strftime('%Y-%m-%d %H:%M:%S') if isinstance(obj, datetime.date): return obj.strftime('%Y-%m-%d %H:%M:%S') else: return json.JSONEncoder.default(self, obj) import json import datetime a = datetime.datetime.now() print(a) b = json.dumps(a,cls=CJsonEncoder) print(b)
执行结果:
2017-02-05 10:29:05.308121 "2017-02-05 10:29:05"