转换json时出现了
TypeError: datetime.datetime(2015, 9, 11, 18, 12, 7, 679000) is not JSON serializable
因为不能解析datetime格式
解决方案:
# coding: utf-8import jsonimport simplejsonimport functoolsfrom datetime import date, datetimedef date_encoder(obj): 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 super().default(self, obj)class JsonDateEncoder(json.JSONEncoder): def default(self, obj): return date_encoder(obj)class SimplejsonDateEncoder(simplejson.JSONEncoder): def default(self, obj): return date_encoder(obj)if __name__ == '__main__': dic = { 'id': 1, 'name': 'yehun', 'date': datetime.now() } json_func = functools.partial(json.dumps, cls=JsonDateEncoder) print json_func(dic) simplejson_func = functools.partial(simplejson.dumps, cls=SimplejsonDateEncoder) print simplejson_func(dic)