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.
The error TypeError: tuple indices must be integers or slices, not str
is on the stamp = cursor.fetchone()["time"]
line.
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 = timemembers = 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.")
Help would be appreciated.
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"]
to
stamp = cursor.fetchone()[0]
See details at the psychopg.fetchone()
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 returnedcursor.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 elementtimestamp = 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.")