Skip to content Skip to sidebar Skip to footer

TypeError: Tuple Indices Must Be Integers Or Slices, Not Str Postgres/python

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 indi

Solution 1:

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 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.")

Post a Comment for "TypeError: Tuple Indices Must Be Integers Or Slices, Not Str Postgres/python"