当前位置:   article > 正文

Python报错:datetime.datetime(2021, 1, 6, 18, 0, 36) is not JSON serializable_python datetime报错

python datetime报错

Python报错:datetime.datetime(2021, 1, 6, 18, 0, 36) is not JSON serializable

datetime.datetime(2021, 1, 6, 18, 0, 36) is not JSON serializable

问题背景:
查询sql发现create_time,在返回给前端时,json化报错。

序列化的数据示例:
((118207L, u’acc_register’, u’safemobile_20210106’, 23771L, 24371L, 600L, 600L, datetime.datetime(2021, 1, 6, 18, 0, 26)),)

解决方案:

import json
import datetime
 
class DateEncoder(json.JSONEncoder):
    def default(self,obj):
        if isinstance(obj,datetime.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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在使用json.dumps序列化的时候,调用上面定义的函数即可,如下:

result_json =json.dumps(data, cls=DateEncoder) 
print result_json
  • 1
  • 2

添加之后,重新执行,问题解决。

本人亲测通过!

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号