Python考试题--第52道题目--在JSON格式化时,怎样处理日期时间--2022年04月07日
原创目录
3、使用json.JSONEncoder.default()方法处理Date数据类型。
1.采访主题:Injson如何在序列化时处理日期类型?
1、什么JSON序列化:
就是将Python列表、元组、词典、数字、对象等。---> 转化为json字符串 使用json.dumps()函数
2、JSON序列化可以自动处理哪些类型的数据:
可以处理str、int、list、tuple、dict、bool、None,但不能自动处理。datetime数据类型。
3、使用json.JSONEncoder.default()方法处理Date数据类型。
2.示例代码演示了如何处理日期类型:
1,创建一个类Datatojson:
import json
from datetime import datetime, date
class Datatojson(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
# return obj.strftime("%Y年%m月%d日 %H时%M分%S秒")
return obj.strftime("%Y-%m-%d %H:%M:%S")
elif isinstance(obj, date):
# return obj.strftime("%Y年%m月%d日")
return obj.strftime("%Y-%m-%d")
else:
return json.JSONEncoder.default(self, obj)
2,处理日期类型的词典:
import json
from datetime import datetime, date
d = {name: bill, date: datetime.now()}
print(json.dumps(d))
# 通过这种方式,直接序列化词典将报告错误。
# TypeError: Object of type datetime is not JSON serializable
# 直译:TypeError:datetime类型的对象不能为JSON序列化
3,引用上面的类可以解决这个问题:
import json
from datetime import datetime, date
class Datatojson(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
# return obj.strftime("%Y年%m月%d日 %H时%M分%S秒")
return obj.strftime("%Y-%m-%d %H:%M:%S")
elif isinstance(obj, date):
# return obj.strftime("%Y年%m月%d日")
return obj.strftime("%Y-%m-%d")
else:
return json.JSONEncoder.default(self, obj)
d = {name: bill, date: datetime.now()}
print(d)
print(json.dumps(d,cls=Datatojson))
结果如下:

3.在此过程中遇到的其他问题:
自己创建Datatojson类中,设置日期类型的格式。如果格式中有中文字符,则会报告错误。届时,所有的字符都将匆忙地改为英文字符,而不是中文。
报告内容时出错:
发生异常: UnicodeEncodeError
locale codec cant encode character \u5e74 in position 2: encoding error

稍后查阅数据,了解原因以及如何处理此类问题。我还写了一篇关于这个问题的文章。所附地址 Python使用time.strftime报错:‘locale‘ codec can‘t encode character ‘\u5e74‘ in position 2: encoding error_蓝星部队博客-CSDN博客
https://blog.csdn.net/lanxingbudui/article/details/124018316
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123



