您的位置:首页 > 编程语言 > Python开发

python整理二十四——让simplejson支持datetime类型的序列化

2009-02-13 21:19 696 查看
simplejson是python的一个json包,但是觉得有点不爽,就是不能序列化datetime,稍作修改就可以了:

# 可以序列化时间的json
import datetime
import decimal
import simplejson

def safe_new_datetime(d):
kw = [d.year, d.month, d.day]
if isinstance(d, datetime.datetime):
kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo])
return datetime.datetime(*kw)

def safe_new_date(d):
return datetime.date(d.year, d.month, d.day)

class DatetimeJSONEncoder(simplejson.JSONEncoder):
"""可以序列化时间的JSON"""

DATE_FORMAT = "%Y-%m-%d"
TIME_FORMAT = "%H:%M:%S"

def default(self, o):
if isinstance(o, datetime.datetime):
d = safe_new_datetime(o)
return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
elif isinstance(o, datetime.date):
d = safe_new_date(o)
return d.strftime(self.DATE_FORMAT)
elif isinstance(o, datetime.time):
return o.strftime(self.TIME_FORMAT)
elif isinstance(o, decimal.Decimal):
return str(o)
else:
return super(DatetimeJSONEncoder, self).default(o)


#e.g

d1= {'name' : 'hong', 'dt' : datetime.datetime.now()}

simplejson.dumps(d1,cls=DatetimeJSONEncoder)

就这么简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: