python解决json序列化时间格式
简单实例
import json from datetime import datetime from datetime import date info = { "name": "ffm", "birth": datetime.datetime.now(), "age": 18, 'hobbies': ['music', 'read', 'dancing'], 'addr': { 'country': 'China', 'city': 'shanghai' } } class CJsonEncoder(json.JSONEncoder): def default(self, 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 json.JSONEncoder.default(self, obj) json_info=json.dumps(info, cls=CJsonEncoder)
#进一步的进阶使用,将MongoDB和sqlalchemy加入 from datetime import date, datetime # MongoDB的id from bson import ObjectId import json # sqlalchemy的元类 from sqlalchemy.ext.declarative import DeclarativeMeta class JSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, datetime): return obj.strftime('%Y/%m/%d %H:%M:%S') elif isinstance(obj, date): return obj.strftime('%Y-%m-%d') # 如果是MongoDB的id,将其转成字符串 elif isinstance(obj, ObjectId): return str(obj) elif isinstance(obj, bytes): return obj.decode() # 如果是sqlalchemy数据库对象将其拆分,拼接成字典 elif isinstance(obj.__class__, DeclarativeMeta): res = {} for key in obj.__dict__: if key[0] != "_": res[key] = obj.__dict__[key] return res else: return json.JSONEncoder.default(self, obj)