Python类型错误:';datetime.datetime';对象不可下标

Python类型错误:';datetime.datetime';对象不可下标,python,datetime,Python,Datetime,我在python脚本中有一个查询,它连接到sql数据库并检索相应行的(datetime,Id)对。我需要遍历结果集,并分别过滤掉“datetime”和“Id”部分。 我的目的是为每一行获取“Id”。因此,在下面的查询中,我需要过滤掉“275”(见下文) 在编写此脚本时: cursor2.execute(query2, [item[0]]) values = cursor2.fetchone() #values now equals = (datetime.datetime(2015, 7, 2

我在python脚本中有一个查询,它连接到sql数据库并检索相应行的(datetime,Id)对。我需要遍历结果集,并分别过滤掉“datetime”和“Id”部分。 我的目的是为每一行获取“Id”。因此,在下面的查询中,我需要过滤掉“275”(见下文)

在编写此脚本时:

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”对象不可订阅


我曾尝试将值转换为列表/字符串对象,但到目前为止没有任何效果。有什么想法吗?

如果您只是想获得完整的
datetime
对象,那么只需使用
值[0]
,而不是
值[0][0]
。对于
Id
使用
值[1]
。范例-

>>> values = (datetime.datetime(2015, 7, 22, 17, 17, 36), 275)
>>> print(values[1])
275
for dateobj, id in cursor.fetchall():
    #Do your logic with `id`.
values[0]
引用了
datetime
对象,因此当您执行
values[0][1]
时,您试图在datetime对象上使用下标,这是不可能的,因此会出现错误

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

>>> values = (datetime.datetime(2015, 7, 22, 17, 17, 36), 275)
>>> print(values[1])
275
for dateobj, id in cursor.fetchall():
    #Do your logic with `id`.

调用
.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)

要得到275,你只需要

print(values[1])
假定

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

通过使用
值[0][0]
,您想得到什么?Hi刚刚更新了问题。所以我需要在结果集中得到的每一行的“Id”部分。