2015-09-25 1069 views
2

我在python脚本中查询了一个连接到sql数据库并且为相应行检索(datetime,id)对的脚本。我需要遍历结果集并分别过滤掉'datetime'和'Id'部分。 我的意图是为每行获得'Id'。因此,在下面的查询我需要过滤掉“275”(见下文)Python TypeError:'datetime.datetime'对象不是可订阅的

在写这个剧本:

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

我得到这个错误:

TypeError: 'datetime.datetime' object is not subscriptable

我曾尝试转换值到一个列表/字符串对象,但目前为止还没有工作。有任何想法吗?

+0

什么是你想获得使用'值[0] [0]'? –

+0

嗨刚刚更新了这个问题。所以我需要结果集中每行的“Id”部分。 – 90abyss

回答

2

如果您只是试图获得完整的datetime对象,则只需使用values[0]而不是values[0][0]。而对于Id则使用values[1]。示例 -

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

values[0]datetime对象,所以当你做values[0][1],您试图DateTime对象,这是不可能的使用下标,因此错误。

这是因为您使用的是cursor.fetchone(),它只返回一行作为元组。如果你使用的是.fetchall().fetchmany(),那么你得到的将是一个元组列表,并且在这种情况下,你可以迭代列表,每次取一个元组,并得到索引为1的元素。示例 -

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

,当你调用.fetchone()你得到一个元组(一个记录):

mydate, myid = cursor.fetchone() 

,如果你只是想获得id的每一行,你可以这样做:

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

一般来说,最好只选择你需要的数据,也许:

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) 
1

要得到275,你只需要

print(values[1]) 

假设

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