Python datetime 转 JSON

Python datetime 转 JSON

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)
posted @ 2019-04-16 10:10  吴思老  阅读(1771)  评论(0编辑  收藏  举报