TypeError:元组索引必须是整数或切片,而不是str postgres / python [英] TypeError: tuple indices must be integers or slices, not str postgres/python
问题描述
我正在尝试从postgres数据库中名为time的行获取时间戳,但是我遇到了错误。这是数据库中的第二行。
Hi I'm trying to get a timestamp from a row called time in my postgres database, however I'm getting the error. It's the second row in the database.
错误 TypeError:元组索引必须是整数或切片,而不是str
在 stamp = cursor.fetchone()[ time]
行。
我希望将元组在字符串中读取为字符串我的不和谐机器人。这是我要处理的内容:
I would like the tuple to be read as as string in my discord bot. Here is what I'm dealing with:
for member in guild.members:
cursor = conn.cursor()
cursor.execute("SELECT time FROM blacklist WHERE username=%s", (member.id, ))
stamp = cursor.fetchone()["time"]
for time in stamp:
if time is not None:
timestamp = time
members = discord.utils.get(member.guild.roles, name="Members")
restricted_role = get(guild.roles, name="Restricted")
datestamp = datetime.now()
datetimestring = str(datestamp.now().strftime("%Y%m%d%H%M%S"))
dateonlystring = timestamp.strftime("%Y%m%d%H%M%S")
if (datetimestring > dateonlystring):
await member.add_roles(members)
await member.remove_roles(restricted_role)
print("Done.")
我们将不胜感激。
推荐答案
此代码段存在一些问题。引发此错误的原因是 cursor.fetchone()
返回一个元组
,而不是 dict
提示错误。您需要给它一个整数索引,该索引对应于名为 time的列。在返回定义中,该值应该为0。
There are a few problems with this code snippet. The one that throws this error is that cursor.fetchone()
returns a tuple
, not at dict
as the error suggests. You need to give it the integer index that correspond to the column named "time" in your return definition, this should be 0.
因此,您需要更改以下行:
So you need to change the line:
stamp = cursor.fetchone()["time"]
至
stamp = cursor.fetchone()[0]
但是,我注意到应该对 stamp
进行索引,因此即使您测试了 None
,该操作也会失败。
However, I noticed that stamp
should be indexed, so that will fail even if you test for None
.
我根据修改后的代码提出了其他建议。
I made other suggestions in the revised code, based on what it does presumably.
for member in guild.members:
cursor = conn.cursor()
# Changed the query so that NULLs (which will be cast as None) are not returned
cursor.execute("SELECT time FROM blacklist WHERE username=%s AND time IS NOT NULL", (member.id, ))
# no index needed, multiple stamps are returned
results = cursor.fetchall()
for result in results:
# first and only returned element
timestamp = result[0]
members = discord.utils.get(member.guild.roles, name="Members")
restricted_role = get(guild.roles, name="Restricted")
datestamp = datetime.now()
datetimestring = str(datestamp.now().strftime("%Y%m%d%H%M%S"))
dateonlystring = timestamp.strftime("%Y%m%d%H%M%S")
if (datetimestring > dateonlystring):
await member.add_roles(members)
await member.remove_roles(restricted_role)
print("Done.")
这篇关于TypeError:元组索引必须是整数或切片,而不是str postgres / python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!