zoukankan      html  css  js  c++  java
  • Django序列化时间报错

    一、前言

    当利用models模块从数据库获取数据时,当获的取数据序列化时,如果获取的数据中有关于时间类型的字段,则会报错,错误如下:

    TypeError: datetime.datetime(2018, 8, 28, 10, 31, 56, 158078) is not JSON serializable

    二、解决方法

    import json
    from datetime import date, datetime
    class MyEncoder(json.JSONEncoder):
        def default(self, obj):
            # if isinstance(obj, datetime.datetime):
            #     return int(mktime(obj.timetuple()))
            if isinstance(obj, 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)

    三、测试

    import json
    from datetime import date, datetime
    data = [
        {
            'id': 2,
            'hostname': 'openstack',
            'create_date': datetime(2018, 8, 28, 10, 31, 56, 158078),
            'ip': '10.0.0.12',
            'mod_date': datetime(2018, 8, 28, 10, 31, 56, 158078),
            'detail': '云计算',
            'servertype__serverName': 'openstack',
        }
    ]
    
    class MyEncoder(json.JSONEncoder):
        def default(self, obj):
            # if isinstance(obj, datetime.datetime):
            #     return int(mktime(obj.timetuple()))
            if isinstance(obj, 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)
    
    print(json.dumps(data, cls=MyEncoder))

     输出结果:

    [
        {
            "id": 2,
            "ip": "10.0.0.12",
            "mod_date": "2018-08-28 10:31:56",
            "servertype__serverName": "backup",
            "hostname": "openstack",
            "create_date": "2018-08-28 10:31:56",
            "detail": "u4e91u8ba1u7b97"
        }
    ]
  • 相关阅读:
    XML与JSON的对比
    WPF dataGrid下的ComboBox的绑定
    WPF 导出Excel(合并单元格)
    WPF x:key和x:name用法
    WPF Canvas
    WPF Visibility属性用法
    AxInterop.ShockwaveFlashObjects.dll 问题
    BadImageFormatException,未能加载正确的程序集XXX的解决办法
    inner join ,left join ,right join区别
    Mac系统下php.ini的位置
  • 原文地址:https://www.cnblogs.com/wutao666/p/9547007.html
Copyright © 2011-2022 走看看