Python datetime 转 JSON

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

环境:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
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)
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄