一、前言

当利用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": "\u4e91\u8ba1\u7b97"
}
]

Django序列化时间报错的更多相关文章

  1. django startproject xxx:报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 13: ordinal not in range(128)

    django startproject xxx:报错UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 13: o ...

  2. Django迁移数据库报错

    Django迁移数据库报错 table "xxx" already exists错误 django在migrate时报错django migrate error: table 'x ...

  3. django正常运行确报错的解决方法

    django正常运行却报错的处理方法 出处 : https://www.infvie.com/ops-notes/django-normal-operation-error 报错一:self._soc ...

  4. Django:django-cors-headers 报错no module named "corsheaders"

    django跨域使用 pip install django-cors-headers 然后在settings文件中加上参数设置 # app配置 INSTALLED_APPS = [ 'django.c ...

  5. django调用py报错 django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured.

    完整报错信息如下 django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, bu ...

  6. django 连接mysql报错

    原因: 问题1. 即从mysql5.7版本之后,默认采用了caching_sha2_password验证方式. 问题2.  然后在执行 python manage.py makemigrations依 ...

  7. Django创建App报错

    在django下创建APP项目时遇到的坑 python manage.py startapp app01 报错内容如下: 解决:找到报错中的文件夹151行删除items(),)中的逗号即可 在命令行下 ...

  8. Django 使用allauth报错

    一:报错 RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_labe ...

  9. Python Django 协程报错,进程池、线程池与异步调用、回调机制

    一.问题描述 在Django视图函数中,导入 gevent 模块 import gevent from gevent import monkey; monkey.patch_all() from ge ...

随机推荐

  1. 基于Vue的日历组件

    可以标注重要日子 自己写的,可能不是特别很好,大家多提意见!!! 地址:https://github.com/jsLWQ/calendar

  2. HashMap的源码学习以及性能分析

    HashMap的源码学习以及性能分析 一).Map接口的实现类 HashTable.HashMap.LinkedHashMap.TreeMap 二).HashMap和HashTable的区别 1).H ...

  3. 软件测试从业者必备的高频Linux命令

    命令 cd 1.如何进入上级目录 cd .. 2.如何进入当前用户主目录 cd ~ 3.如何进入上两级目录 cd ../.. 4.进入当前目录命令 cd . 5.如何进入目录 /usr/isTeste ...

  4. Openlayers ol.interaction.Select传值问题

    说明: 在使用ol.interaction.Select时,我定义的变量作用域作用不到其回调函数里,但我在select结果中,需要用到这些变量 解决方案: 虽想了个办法解决了,但不知道是不是合理:是否 ...

  5. PostGIS 存储过程返回类型

    Postgresql存储过程返回值的方式有很多,在此先只记录一下自己用到过的,慢慢拓展 1.type型,这里geometry可以是任何postgresql支持的类型(integer/text/char ...

  6. Code Helper占用大量CPU和内存

    项目架构: React+TS+DVA 设备及软件: 设备:Mac 软件:VSCode 场景: 在Mac中使用VSCode运行时发现项目编译非常卡顿,时间长达五六分钟以上,并且项目启动后访问页面,页面也 ...

  7. JVM系列一(Java内存区域和对象创建).

    一.JVM 内存区域 堆 - Heap 线程共享,JVM中最大的一块内存,此内存的唯一目的就是存放对象实例,Java 堆是垃圾收集器管理的主要区域,因此很多时候也被称为"GC堆"( ...

  8. c# 为什么会出现死锁?多线程死锁怎么解决

    出现死锁必须满足以下几个条件: 1.互斥条件:该进程拥有的资源,其他进程只能等待其释放. 2.不剥夺条件:该进程拥有的资源只能由它自己来释放. 3.请求和保持条件:请求其他的资源,同时自己拥有的资源又 ...

  9. Linux下搭建web服务

    第一:安装java 第二:安装tomcat 第三:部署程序 第一:安装java 下载地址: http://www.oracle.com/technetwork/java/javase/download ...

  10. redis数据类型--hash

    /** Redis应用之Hash数据类型* 问题1:操作命令* 问题2:存储实现原理和数据结构* 问题3:应用场景* */ 先了解下什么是hash,什么是hash碰撞:hash:是包含键值对的kv的数 ...