如何使用 psycopg 将时间戳字符串插入到 postgres 数据库中?
How to insert a timestamp string into postgres db with psycopg?
我有一个table:
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 在我的 table 上执行这个命令。
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)来引入命令。
上面的字符串命令的正确格式是什么,以便将时间戳写入 table?
我试过:
"""...,'ts {2020-01-01 00:00:00.001}', ..."""
-> timestamp
类型的无效输入语法
"""...,"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”不存在
此 {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.
我有一个table:
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 在我的 table 上执行这个命令。
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)来引入命令。 上面的字符串命令的正确格式是什么,以便将时间戳写入 table?
我试过:
"""...,'ts {2020-01-01 00:00:00.001}', ..."""
-> timestamp
类型的无效输入语法
"""...,"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”不存在
此 {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.