我正在尝试使用Psycopg2将datetime值插入到我的postgres数据库中。
我的代码以前是可以工作的,但是我从%s表示法切换到{}表示法后,我的代码崩溃了。
以下是我的代码:
for j in eveLists.itemList:
tempPrice = fetchSellPrice(i, j)
database_name = eveLists.DatabaseDict[i]
now = datetime.datetime.utcnow()
cur.execute("INSERT INTO {0} VALUES ({1}, {2}, {3}, NULL, {4}, {5}, NULL);".format(
database_name,
str(i),
str(j),
float(tempPrice),
datetime.date.today(),
now))
我遇到了如下错误:
psycopg2.ProgrammingError: syntax error at or near "00"
LINE 1: ...0000142, 2268, 3.11, NULL, 2017-05-09, 2017-05-10 00:40:03.3...
^
这是将日期和时间视为两个独立的对象。
我尝试了几种不同的方法,但所有的方法都被注释掉并抛出各种错误消息。我尝试了在datetime中加引号的方式,
now = ("'%s'") % str(datetime.datetime.utcnow())
出现错误的地方
psycopg2.ProgrammingError: column "mydate" is of type date but expression is of type integer
LINE 1: ...NTO temp_jita VALUES (30000142, 2268, 3.11, NULL, 2017-05-09...
^
HINT: You will need to rewrite or cast the expression.
它认为我的日期是一个整数,尽管我用引号括起来了。
我还尝试手动创建一个psycopg2时间戳:
now = psycopg2.Timestamp(now.strftime("%Y"),
now.strftime("%m"),
now.strftime("%d"),
now.strftime("%h"),
now.strftime("%M"),
int(now.strftime("%-S")))
这会导致以下错误:
int(now.strftime("%-S")))
TypeError: an integer is required (got type str)
我不知道它为什么认为这是一个字符串,尤其是因为我将它转换成了整数!
任何帮助都将不胜感激。
编辑:我使用 {} 符号而不是 %s 符号传递变量的原因是因为我在以下代码中收到了错误提示:
for j in eveLists.itemList:
tempPrice = fetchSellPrice(i, j)
database_name = eveLists.DatabaseDict[i]
now = datetime.datetime.utcnow()
now = str(now)
cur.execute("INSERT INTO %s VALUES (%s, %s, %s, NULL, %s, %s, NULL);", [database_name,
str(i),
str(j),
float(tempPrice),
datetime.date.today(),
now
])
psycopg2.ProgrammingError: syntax error at or near "'temp_jita'"
LINE 1: INSERT INTO 'temp_jita' VALUES ('30000142', '2268', 3.03, NU...
^
请参考我之前发布的关于此主题的帖子:如何在Python中从字符串中删除引号以供SQL查询? 编辑:根据@Zorg在此链接(https://www.psycopg.org/docs/usage.html)中的建议,以下代码对我有效:
cur.execute(sql.SQL("INSERT INTO {} VALUES (%s, %s, %s, NULL, %s, %s, NULL);").format(sql.Identifier(database_name)),[
str(i),
str(j),
float(tempPrice),
datetime.date.today(),
now
])