【问题标题】:How to insert a timestamp string into postgres db with psycopg?如何使用 psycopg 将时间戳字符串插入 postgres db?
【发布时间】:2020-10-01 18:27:37
【问题描述】:

我有一张桌子:

CREATE TABLE TABLE_WITH_A_TIMESTAMP
(
   TIMESTAMP_ID varchar(4),
   TIMESTAMP timestamp
)

还有一个可与其他工具一起使用的 INSERT 命令: INSERT INTO "my_schema"."table_with_a_timestamp" (timestamp_id, timestamp) VALUES ('0001', {ts '2020-01-01 00:00:00.001'});

现在我想使用 psycopg2 在我的桌子上执行这个命令。

query = """INSERT INTO "my_schema"."table_with_a_timestamp" (timestamp_id, timestamp) VALUES ('0001', {ts '2020-01-01 00:00:00.001'});"""
cursor.execute(query)

这样不行,报错信息是:

syntax error at or near "{"
LINE 1: ...rsion) VALUES ('0001',{ts '2020-...
                                                             ^
: ProgrammingError
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 35, in lambda_handler
    cursor.execute(query)
psycopg2.ProgrammingError: syntax error at or near "{"
LINE 1: ...rsion) VALUES ('0001',{ts '2020-...

有类似的问题将时间戳作为 python 对象处理。但是我不希望解析命令,转换为 python 时间戳,然后进行字符串插值。因为无论如何我都是从文件中读取命令,所以我更愿意以正确的格式(不一定在 python 中)提供命令。 上面的字符串命令的正确格式是什么,以便将时间戳写入表?

我试过了: """...,'ts {2020-01-01 00:00:00.001}', ...""" -> 类型时间戳的无效输入语法
"""...,"ts {'2020-01-01 00:00:00.001'}", ...""" -> 列“{ts '2001-08-13 10:19:47.701'}”不存在
"""...,ts '2020-01-01 00:00:00.001', ...""" -> 类型“ ts" 不存在

【问题讨论】:

    标签: python sql postgresql sql-insert psycopg2


    【解决方案1】:

    这个{ts '2020-01-01 00:00:00.001'} 是特定于其他工具的。 Postgres 正确的语法是

    INSERT INTO "my_schema"."table_with_a_timestamp" (timestamp_id, timestamp) 
    VALUES ('0001', timestamp '2020-01-01 00:00:00.001');
    

    虽然在这种情况下不需要 timestamp 这个词,但请参阅 Db<>Fiddle.

    【讨论】:

      猜你喜欢
      • 2018-01-15
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      相关资源
      最近更新 更多