Python 执行重写或强制转换表达式所需的值

Python 执行重写或强制转换表达式所需的值,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,我正在尝试对具有模式的表执行大容量插入 CREATE TABLE IF NOT EXISTS test (symbol VARCHAR(16), ts timestamp) 我有一个要插入表单的值数组 [('AAPL',1528004700), ('AAPL', 1528005600)] 我的insert查询如下所示 insert into test VALUES %s 我执行插入的python代码如下所示 psycopg2.extras.execute_values(cursor, in

我正在尝试对具有模式的表执行大容量插入

CREATE TABLE IF NOT EXISTS test (symbol VARCHAR(16), ts timestamp)
我有一个要插入表单的值数组

[('AAPL',1528004700), ('AAPL', 1528005600)]
我的insert查询如下所示

insert into test VALUES %s
我执行插入的python代码如下所示

psycopg2.extras.execute_values(cursor, insert_stmt, [('AAPL',1528004700), ('AAPL', 1528005600)])
我犯了一个错误

ProgrammingError: column "ts" is of type timestamp without time zone but expression is of type integer
LINE 1: insert into test VALUES ('AAPL',1528004700),('AAPL',15280056...
                                        ^
HINT:  You will need to rewrite or cast the expression.
我知道,插入时,时间戳可以解决此问题,但执行值不允许我添加多个占位符,每次都需要执行批量插入。时间戳应该没有时区。如何修复此错误

谢谢

更新1

execute_batch()工作得非常好,因为我可以在占位符部分中添加时间戳

insert = "insert into test VALUES (%s, to_timestamp(%s))"

psycopg2.extras.execute_batch(cur, insert, [('AAPL',1528004700), ('AAPL', 1528005600)])
但是,我希望使用execute_值,因为它比execute_batch()稍快一些。

这应该可以:

from datetime import datetime
psycopg2.extras.execute_values(cursor, insert_stmt, [('AAPL',datetime.fromtimestamp(1528004700)), ('AAPL', datetime.fromtimestamp(1528005600))])
编辑: 一般来说,Postgres无法猜测您的1528004700是一个时间戳,您需要以某种方式明确声明它。使用to_timestamp的解决方案将“this is a timestamp”放在Postgres端,代码上方将其放在python端。从信息的角度来看,它们是等效的,我没有检查哪个更有效。

这应该可以:

from datetime import datetime
psycopg2.extras.execute_values(cursor, insert_stmt, [('AAPL',datetime.fromtimestamp(1528004700)), ('AAPL', datetime.fromtimestamp(1528005600))])
编辑:
一般来说,Postgres无法猜测您的1528004700是一个时间戳,您需要以某种方式明确声明它。使用to_timestamp的解决方案将“this is a timestamp”放在Postgres端,代码上方将其放在python端。从信息的角度来看,它们是等效的,我没有检查哪一个更有效。

我不确定
psycopg2.extras.execute\u value
但通常的方法是使用
executemany
方法插入记录列表

insert语句是用
%s
为每列编写的。在这种特殊情况下,我们还需要将整数转换为时间戳。幸运的是,postgresql提供了一个to_时间戳函数来实现这一点

values = [('AAPL',1528004700), ('AAPL', 1528005600)]
stmt = 'insert into test values (%s, to_timestamp(%s))'
cur.executemany(stmt, values)

我不确定是否有
psycopg2.extras.execute\u值
,但通常的方法是使用
executemany
方法插入记录列表

insert语句是用
%s
为每列编写的。在这种特殊情况下,我们还需要将整数转换为时间戳。幸运的是,postgresql提供了一个to_时间戳函数来实现这一点

values = [('AAPL',1528004700), ('AAPL', 1528005600)]
stmt = 'insert into test values (%s, to_timestamp(%s))'
cur.executemany(stmt, values)

感谢您的回答,但是executemany对于大容量插入没有那么有效,最慢的方法是executemany,而最快的方法是executemany,execute batch比execute values慢1%。感谢您的回答,但是executemany对于大容量插入没有那么有效,最慢的方法是executemany,而最快的方法是executevalues,executebatch比executevalues慢1%