简体   繁体   中英

Python TypeError: 'datetime.datetime' object is not subscriptable

I've a query inside python script which connects to the sql database and retrieves a (datetime, Id) pair for that respective row. I need to iterate through the result set and filter out the 'datetime' and 'Id' part separately. My intention is to get 'Id' for each row. So in the following query I need to filter out "275" (see below)

On writing this script:

cursor2.execute(query2, [item[0]])
values = cursor2.fetchone() 
#values now equals = (datetime.datetime(2015, 7, 22, 17, 17, 36), 275)
print(values[0][1])

I get this error:

TypeError: 'datetime.datetime' object is not subscriptable

I have tried converting values to a list/string objects but nothing has been working so far. Any ideas?

If you are simply trying to get the complete datetime object, then simply use values[0] , instead of values[0][0] . And for Id use values[1] . Example -

>>> values = (datetime.datetime(2015, 7, 22, 17, 17, 36), 275)
>>> print(values[1])
275

values[0] refers to the datetime object , so when you do values[0][1] , you are trying to use subscript on the datetime object, which is not possible, and hence the error.

This is because you are using cursor.fetchone() , which only returns you a single row as a tuple. If you were instead using .fetchall() or .fetchmany() , then what you get would be a list of tuples and in that case as well, you can iterate over the list , taking one tuple at a time, and getting the element at index 1 . Example -

for dateobj, id in cursor.fetchall():
    #Do your logic with `id`.

when you call .fetchone() you get back a tuple (one record):

mydate, myid = cursor.fetchone()

if you just want to get the id for each row you could do:

ids = [record[1] for record in cursor.fetchall()]

generally, it's better to only select the data you need though, maybe:

cursor.execute("select id from ({subquery}) t".format(subquery=query2), [item[0]])   # assuming the id column is named id
ids = [record[0] for record in cursor.fetchall()]  # now we're only retrieving one column (index zero)

To get 275, you just need

print(values[1])

assuming

values == (datetime.datetime(2015, 7, 22, 17, 17, 36), 275)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM