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": "\u4e91\u8ba1\u7b97"
}
]
Django序列化时间报错的更多相关文章
- 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 ... 
- Django迁移数据库报错
		Django迁移数据库报错 table "xxx" already exists错误 django在migrate时报错django migrate error: table 'x ... 
- django正常运行确报错的解决方法
		django正常运行却报错的处理方法 出处 : https://www.infvie.com/ops-notes/django-normal-operation-error 报错一:self._soc ... 
- Django:django-cors-headers 报错no module named "corsheaders"
		django跨域使用 pip install django-cors-headers 然后在settings文件中加上参数设置 # app配置 INSTALLED_APPS = [ 'django.c ... 
- 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 ... 
- django 连接mysql报错
		原因: 问题1. 即从mysql5.7版本之后,默认采用了caching_sha2_password验证方式. 问题2. 然后在执行 python manage.py makemigrations依 ... 
- Django创建App报错
		在django下创建APP项目时遇到的坑 python manage.py startapp app01 报错内容如下: 解决:找到报错中的文件夹151行删除items(),)中的逗号即可 在命令行下 ... 
- Django 使用allauth报错
		一:报错 RuntimeError: Model class django.contrib.sites.models.Site doesn't declare an explicit app_labe ... 
- Python Django 协程报错,进程池、线程池与异步调用、回调机制
		一.问题描述 在Django视图函数中,导入 gevent 模块 import gevent from gevent import monkey; monkey.patch_all() from ge ... 
随机推荐
- 多线程编程(3)——synchronized原理以及使用
			一.对象头 通常在java中一个对象主要包含三部分: 对象头 主要包含GC的状态..类型.类的模板信息(地址).synchronization状态等,在后面介绍. 实例数据:程序代码中定义的各种类型的 ... 
- Centos7安装redis5.0.7
			1. 安装依赖包 yum install -y gcc gcc-c++ 2. 下载最新版redis安装包并解压安装 cd /usr/local/src wget http://download.red ... 
- Asp.net Core 系列之--5.认证、授权与自定义权限的实现
			ChuanGoing 2019-11-24 asp.net core系列已经来到了第五篇,通过之前的基础介绍,我们了解了事件订阅/发布的eventbus整个流程,初探dapper ORM实现,并且简单 ... 
- Mac安装和卸载Mysql
			目录 一.安装 二.环境变量 2.1 MySQL服务的启停和状态的查看 三.启动 四.初始化设置 4.1 退出sql界面 五.配置 5.1 检测修改结果 一.安装 第一步:打开网址,https://w ... 
- 解决django或者其他线程中调用scrapy报ReactorNotRestartable的错误
			官网中关于ReactorNotRestartable的错误描述(摘自:https://twistedmatrix.com/documents/16.1.0/api/twisted.internet.e ... 
- ArcGIS 问题汇总
			1.Arcgis10.4出现Manager打不开的情况 解决方法: 1.检查进程中是否有占用4000以及6080端口的进程,如果有关闭 2.检查进程中是否有javaw.exe这个进程,如果有就把他结束 ... 
- 2019-9-11:渗透测试,Kill远控软件,初接触
			初步使用Kill远控软件,使win7靶机被远控 该文章仅供学习,利用方法来自网络文章,仅供参考 1,打开运行Kill,选择系统设置,设置监听端口,通讯密码,点击保存设置 2,点击服务生成,上线参 ... 
- enable_shared_from_this用法分析
			一.背景 在为什么需要异步编程文章末尾提到,"为了使socket和缓冲区(read或write)在整个异步操作的生命周期一直保持活动,我们需要采取特殊的保护措施.你的连接类需要继承自enab ... 
- word2vec:CBOW和skip-gram模型
			1.CBOW模型 之前已经解释过,无论是CBOW模型还是skip-gram模型,都是以Huffman树作为基础的.值得注意的是,Huffman树中非叶节点存储的中间向量的初始化值是零向量,而叶节点对应 ... 
- Java并发编程:Callable、Future和FutureTask【转】
			原文链接:http://www.cnblogs.com/dolphin0520/p/3949310.html 创建线程的2种方式,一种是直接继承Thread,另外一种就是实现Runnable接口. 这 ... 
