问题:转换时间报错
执行代码为:
import json from datetime import date,datetime d = {"time1":date.today(),"time2":datetime.today()} res = json.dumps(d) # 报错
TypeError: Object of type date is not JSON serializable
方案1:
- 手动转换str()
方案2:
- 继承类
-
import json from datetime import date,datetime class MyJsonEncoder(json.JSONEncoder): def default(self, o:str): if isinstance(o,datetime): # print("找到2") return o.strftime("%Y-%m-%d %X") if isinstance(o,date): # print("找到1") return o.strftime("%Y-%m-%d") return o d = {"time1":date.today(),"time2":datetime.today()} print(type(date.today()),type(datetime.today())) # res = json.dumps(d) # 报错 res = json.dumps(d,cls=MyJsonEncoder) print(res)
标签:res,datetime,json,源码,报错,date,序列化,today From: https://www.cnblogs.com/liqi175/p/17350504.html