Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python psycopg2 execute返回日期时间而不是字符串_Python_Psycopg2 - Fatal编程技术网

Python psycopg2 execute返回日期时间而不是字符串

Python psycopg2 execute返回日期时间而不是字符串,python,psycopg2,Python,Psycopg2,这给了我一个例子:- cur.execute("SELECT \ title, \ body, \ date \ # This pgsql type is date FROM \ table \ WHERE id = '%s';", id) response = cur.fetchall() print respo

这给了我一个例子:-

cur.execute("SELECT \
                title, \
                body, \
                date \ # This pgsql type is date
             FROM \
                table \
             WHERE id = '%s';", id)

response = cur.fetchall()

print response
它不能传递给像json.dumps这样的东西,所以我必须这样做:-

[('sample title', 'sample body', datetime.date(2012, 8, 5))]

这感觉很糟糕,有人知道更好的处理方法吗?

首先,您希望从带有“日期”数据类型的字段返回什么?明确地说,日期,驱动程序显然在这里按预期执行

因此,您的任务实际上是了解如何使用json编码器对
datetime.date
类的实例进行编码。答案很简单,通过对内置编码器进行子类化来改进编码器:

processed = []

for row in response:
    processed.append({'title' : row[0], 
                      'body' : row[1], 
                      'date' : str(row[2])
                     })
用法(您需要明确表示您正在使用自定义编码器):


正如前面的答案所示,这是对日期字段进行查询的预期结果。但是,查询本身可以简化很多。 如果你浏览博士后的文档,你可以找到这个函数。 这将导致查询中的简单更改

json.dumps(_your_dict, cls=DateEncoder)
json.dumps(_your_dict, cls=DateEncoder)
cur.execute("SELECT \
            title, \
            body, \
            to_char(date, 'YYY-MM-DD') \ # This pgsql type is date
         FROM \
            table \
         WHERE id = '%s';", id)