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 ...
随机推荐
- php使用cUrl方法 get、post请求
php使用curl方法,请确保已经开启curl扩展.传送门:http://www.cnblogs.com/wgq123/p/7450667.html /**Curl请求get方法 *@$url Str ...
- .Net Core 使用NPOI导入数据
一.搭建环境 1.新建ASP.NET Core Web 应用程序 2.选择API 3.引用Swashbuckle.AspNetCore NuGet 包进行安装. Swashbuckle.AspNetC ...
- MyEclipse使用总结
0.快捷键 ================================================================================ 编辑: Ctrl+Shif ...
- 小白学 Python 爬虫(4):前置准备(三)Docker基础入门
人生苦短,我用 Python 前文传送门: 小白学 Python 爬虫(1):开篇 小白学 Python 爬虫(2):前置准备(一)基本类库的安装 小白学 Python 爬虫(3):前置准备(二)Li ...
- pdf 在线预览之 pdfjs插件
这个插件不需要阅读器 也不会屏蔽签章 但是也是兼容到ie11
- 微信小程序获取二维码(直接上代码)https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=ACCESS_TOKEN
应为是直接返回二进制数据所有与其他接口些许差别,希望能帮助现在的你! 谢谢!!! /** * 37.微信二维码生成 */ public String getWeiXinCourseMap() { ...
- yum运行报错:File "/usr/bin/yum", line 30 except KeyboardInterrupt, e: ^SyntaxError: invalid syntax
这是由于Python升级导致 备份Python 历史版本 [root@sdw1 autoconf]# ls /usr/bin/python* [root@sdw1 autoconf]# mv /usr ...
- Mybatis工作流程源码分析
1.简介 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单 ...
- libgcc_s.so.1 cannot open shared object file No such file or directory
libgcc_s.so.1: cannot open shared object file: No such file or directory解决办法 背景 使用WAR包安装jenkins,在tom ...
- Objective-C (OC)
1.OC 运行效率比较高,仅次于c.开发过程时,效率也比较高,不会次于java和C++: :表示继承 “{}”之间写字段或声明 }和@end之间写函数 import 相当于include 作用于和j ...