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"
        }
    ]
  • 相关阅读:
    leetcode 刷题日志 2018-03-26
    WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping
    sublime wrong
    SSM框架使用-wrong
    C++设计实现算法时易犯错误
    CodeBlocks wrong
    leetcode 刷题日志 2018-3-28
    CountDownLatch
    类加载器和双亲委派
    GC的一个面试题
  • 原文地址:https://www.cnblogs.com/wutao666/p/9547007.html
Copyright © 2011-2022 走看看