gpt4 book ai didi

python - 如何修复 'invalid syntax for type timestamp' Postgres?

转载 作者:行者123 更新时间:2023-11-29 13:21:21 26 4
gpt4 key购买 nike

我正在为这个问题苦苦挣扎

当我运行函数时一切正常:

def total_event(start_date, end_date):
conn = psycopg2.connect(NE_DB_2)
cur = conn.cursor()
payload = """SELECT COUNT("pattern_id") FROM "pattern" WHERE "created_at" < '%(end)s' AND "created_at" > '%(start)s'"""
payload % {'start': start_date, 'end': end_date}
cur.execute(payload)
rows = cur.fetchall()
event_total = str(event_total)
return event_total

但是当我使用定义的变量执行函数时:

start_date = '2016-12-05'
end_date = '2016-12-11'
start_date = datetime.datetime.strptime(start_date,'%Y-%m-%d')
end_date = datetime.datetime.strptime(end_date,'%Y-%m-%d')
event_total = total_event(start_date, end_date)
event_total

它给我这个错误:

DataErrorTraceback (most recent call last)
<ipython-input-46-0979ea389f87> in <module>()
12 start_date = datetime.datetime.strptime(start_date,'%Y-%m-%d')
13 end_date = datetime.datetime.strptime(end_date,'%Y-%m-%d')
---> 14 event_total = total_event(start_date, end_date)
15 event_total

<ipython-input-46-0979ea389f87> in total_event(start_date, end_date)
4 payload = """SELECT COUNT("pattern_id") FROM "pattern" WHERE "created_at" < '%(end)s' AND "created_at" > '%(start)s'"""
5 payload % {'start': start_date, 'end': end_date}
----> 6 cur.execute(payload)
7 rows = cur.fetchall()
8 event_total = str(event_total)

DataError: invalid input syntax for type timestamp: "%(end)s"
LINE 1: ..."pattern_id") FROM "pattern" WHERE "created_at" < '%(end)s' ...

最佳答案

您没有将格式化字符串重新分配给 payload。您仍在传递带有 %(end)s 的变量版本。

改变

payload % {'start': start_date, 'end': end_date}

进入

payload = payload % {'start': start_date, 'end': end_date}

关于python - 如何修复 'invalid syntax for type timestamp' Postgres?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41140248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com