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

yipeiwu_com6年前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 统计字数的思路详解

 问题描述: 用 Python 实现函数 count_words(),该函数输入字符串 s 和数字 n,返回 s 中 n 个出现频率最高的单词。返回值是一个元组列表,包含出现次...

python3使用matplotlib绘制散点图

python3使用matplotlib绘制散点图

本文实例为大家分享了python3使用matplotlib绘制散点图,并标注图例,轴,供大家参考,具体内容如下 代码 from matplotlib import pyplot as...

python使用if语句实现一个猜拳游戏详解

python使用if语句实现一个猜拳游戏详解

任务要求 在控制台中提示输入石头、剪刀、布,按回车键,然后给出游戏结果。 分析 我们知道在游戏规则中,石头克剪刀,剪刀克布,布克石头。但是这在计算机中并不是很好直接的表示,因此我们分别...

9种python web 程序的部署方式小结

主流的web server 一个巴掌就能数出来,apache,lighttpd,nginx,iis application,中文名叫做应用服务,就是你基于某个web framework写...

使用python模拟高斯分布例子

使用python模拟高斯分布例子

正态分布(Normal distribution),也称“常态分布”,又名高斯分布(Gaussian distribution) 正态曲线呈钟型,两头低,中间高,左右对称因其曲线呈钟形,...