Python 中将 datetime 转换为 JSON 类型,在使用 Django 时遇到的问题。

环境:

Python2.7

代码:

import json
import datetime

class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime('%Y-%m-%d')
        else:
            return json.JSONEncoder.default(self, obj)


d = {
  "now": datetime.datetime.now()
}

# 转换发生异常
try:
  json.dumps(d)
except Exception as e:
  print(e)

# 指定 cls 参数,转换成功
str_json = json.dumps(d, cls=ComplexEncoder)
print(str_json)

相关文章:

  • 2021-09-10
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-10
  • 2022-12-23
  • 2021-09-02
猜你喜欢
  • 2022-12-23
  • 2021-06-14
  • 2021-10-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
相关资源
相似解决方案