cur.execute("SELECT \
title, \
body, \
date \ # This pgsql type is date
FROM \
table \
WHERE id = '%s';", id)
response = cur.fetchall()
print response
举个例子,这给了我:-
[('sample title', 'sample body', datetime.date(2012, 8, 5))]
不能传递给 json.dumps 这样的东西,所以我必须这样做:-
processed = []
for row in response:
processed.append({'title' : row[0],
'body' : row[1],
'date' : str(row[2])
})
感觉形式不佳,有谁知道处理此问题的更好方法吗?
最佳答案
首先,您希望从具有“日期”数据类型的字段返回什么?明确地说,日期,并且驱动程序在此处显然按预期执行。
因此,您的任务实际上是了解如何使用 json 编码器对 datetime.date
类的实例进行编码。简单的答案,通过子类化内置编码器来改进编码器:
from datetime import date
import json
class DateEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, date):
return str(obj)
return json.JSONEncoder.default(self, obj)
用法(您需要明确说明您使用的是自定义编码器):
json.dumps(_your_dict, cls=DateEncoder)
关于python - psycopg2 执行返回日期时间而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12316638/