您当前的位置: 首页 >  彭世瑜 json

TypeError: Object of type 'datetime' is not JSON serializable

彭世瑜 发布时间:2019-06-06 17:26:21 ,浏览量:1

json序列化时间对象的时候报错:

    TypeError: Object of type 'datetime' is not JSON serializable

解决办法

重写json序列化类

# -*- coding: utf-8 -*-

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, datetime.date):
            return obj.strftime("%Y-%m-%d")

        else:
            return json.JSONEncoder.default(self, obj)


if __name__ == '__main__':
    data = {"name": "Tom", "birthday": datetime.datetime.now()}
    print(json.dumps(data, cls=DateEncoder))
    # {"name": "Tom", "birthday": "2019-06-06 17:24:19"}

参考: python datetime.datetime is not JSON serializable 报错问题解决

关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 1浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0545s