python2.7 json 转换日期的处理的示例

yipeiwu_com7年前Python基础

python2.7中 集成了json的处理(simplejson),但在实际应用中,从mysql查询出来的数据,通常有日期格式,这时候,会报一个错:

TypeError: datetime.datetime(2007, 7, 23, 12, 24, 25) is not JSON serializable

说明日期转换出问题,后来再网上找到了解决办法。

import json
from datetime import date, datetime


def __default(obj):
  if isinstance(obj, datetime):
    return obj.strftime('%Y-%m-%dT%H:%M:%S')
  elif isinstance(obj, date):
    return obj.strftime('%Y-%m-%d')
  else:
    raise TypeError('%r is not JSON serializable' % obj)

print json.dumps({
    'd': datetime.now(), 
    'today': date.today(), 
    'x': 111
  }, default=__default)

采用类似的方式,在得到mysql数据集后,需要序列化时,用如下方式就可以了。 

conn=self.getConnection();
cursor=conn.cursor();
cursor.execute(sqlText,params);
result=cursor.fetchall()
jsonstr=json.dumps(myresult,default=__default)
print jsonstr

关键点在于覆盖了default 方法。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python开发利器之ulipad的使用实践

python开发利器之ulipad的使用实践

介绍 UliPad是一个国人开发的python轻量级编辑器,导向和灵活的编程器。它如类浏览器,代码自动完成许多功能,如:HTML查看器,目录浏览器,向导等。 下载与安装 下载地址:...

django2.0扩展用户字段示例

创建新项目,及应用 django-admin startproject myproj cd myproj python manage.py startapp myapp 自定义 U...

Python实现求一个集合所有子集的示例

方法一:回归实现 def PowerSetsRecursive(items): """Use recursive call to return all subsets of it...

解决Matplotlib图表不能在Pycharm中显示的问题

解决Matplotlib图表不能在Pycharm中显示的问题

初学者可能都会遇到一个小问题就是:在用IPython的时候,可以使用类似 %matplotlib inline 的Magic Function(魔法函数)来显示Matplotlib...

Python 3.8正式发布,来尝鲜这些新特性吧

今天 Python3.8 发布啦,它是 Python2 终结前最后一个大版本,我们一起看看这个版本都添加了那些新功能和特性。 PEP 572: Assignment Expression...