我有一个基本的词典如下:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
Run Code Online (Sandbox Code Playgroud)
当我尝试做的时候,jsonify(sample)我得到:
TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON serializable
我能做些什么,以便我的字典样本可以克服上述错误?
注意:虽然它可能不相关,但字典是从mongodb中检索记录生成的,当我打印输出时str(sample['somedate']),输出是2012-08-08 21:46:24.862000.
这是我的代码,查询Notification.create_time
result = session.query(
Notification.content, cls.is_read,
Notification.create_time).join(
cls, Notification.id == cls.notification).filter(
and_(cls.user == user_id)).order_by(
Notification.create_time.desc()).all()
Run Code Online (Sandbox Code Playgroud)
在其他地方需要json.dumps查询结果到前端,datetime格式不能json.dumps,所以我想这样做:
session.query(Notification.create_time.strftime('%Y-%m-%d %H:%M'))
Run Code Online (Sandbox Code Playgroud)
那么,如何在sqlalchemy查询中将datetime更改为string?