学习笔记(05):Python 面试100讲(基于Python3.x)-在JSON序列化时如何处理日期类型的值...

立即学习:https://edu.csdn.net/course/play/26755/340158?utm_source=blogtoedu

json可处理的数据类型:string,list,tuple,int,float,dict,bool,null
不可处理的数据类型:datetime
处理方法:需要在转换类的default方法手工完成日期值的处理
'''
json可处理的数据类型:string,list,tuple,int,float,dict,bool,null
不可处理的数据类型:datetime
处理方法:需要在转换类的default方法手工完成日期值的处理
'''
from datetime import datetime,date
import json
class DateTOJson(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj,datetime):
            return obj.strftime('%Y{y}%m{m}%d{d}  %H:%M:%S').format(y='年',m='月',d='日')
        elif isinstance(obj,date):
            return obj.strftime('%Y年%m月%d日')
        else:
            return obj
d={'name':'Jason','content':"Life is short,you need Python",'date':datetime.now()}
print(json.dumps(d,cls=DateTOJson,ensure_ascii=False))
print(type(json.dumps(d,cls=DateTOJson,ensure_ascii=False)))

输出结果如下:

{"name": "Jason", "content": "Life is short,you need Python", "date": "2020年02月27日  21:59:47"}
<class 'str'>

猜你喜欢

转载自blog.csdn.net/Smile_Lai/article/details/104546231