psycopg2 - 多次插入,但插入一个公共时间戳

psycopg2 - multiple insert, but insert one common timestamp

我正在尝试插入多个表,但让它们只共享一个时间戳。我正在实施这样的事情:

for table in table_names:
    current_utc_time = str(datetime.utcnow())
    cursor.execute("INSERT INTO public.{0} VALUES({1}, {2})".format(table, current_utc_time, foo))

但是这组代码抛出以下错误...

Traceback (most recent call last):
  File "C:/Users/EricKim/Documents/sage/fake_data_push.py", line 58, in <module>
    cursor.execute("INSERT INTO public.{0} VALUES({1}, {2})".format(table, current_utc_time, df.iloc[row_num, col_num]))
psycopg2.ProgrammingError: syntax error at or near "16"
LINE 1: INSERT INTO public.rt_torqx VALUES(2018-08-30 16:26:35.20088...

一定是格式错误,但我现在知道出了什么问题,因为据我了解,2018-08-30 16:26:35.20088 是 pgsql 时间戳字符串格式的正确格式。谁能告诉我怎么了?

我建议您不要使用 Python 字符串 format() 作为参数。相反,使用通过 %s 传递的 psycopg2 参数,它将为您进行类型转换。类似于:

right_now = datetime.utcnow()
cursor.execute(f'INSERT INTO public.{table} VALUES(%s, %s)', (right_now, df.iloc[row_num, col_num],))

(未测试,但要点是 1)仅对 table 名称使用 f 字符串(或 .format()),因为这不是参数,以及 2)使用 %s 实参占位符;您可能需要通过 str() 转换 df 值...取决于所讨论的数据类型)

http://initd.org/psycopg/docs/usage.html#passing-parameters-to-sql-queries