让simplejson支持datetime类型的序列化

时间:2023-03-09 06:39:54
让simplejson支持datetime类型的序列化

simplejson是Python的一个json包,但是觉得有点不爽,就是不能序列化datetime,稍作修改就可以了:

原文:http://blog.csdn.net/hong201/article/details/3888588

# 可以序列化时间的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)

调用方法:

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

simplejson.dumps(d1,cls=DatetimeJSONEncoder)