Python TypeError:“datetime.datetime”对象不是subscriptab

2024-04-29 21:24:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python脚本中有一个查询,它连接到sql数据库并为相应的行检索(datetime,Id)对。我需要遍历结果集并分别过滤掉“datetime”和“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' object is not subscriptable

我尝试过将值转换为list/string对象,但到目前为止没有任何工作。有什么想法吗?


Tags: 脚本id数据库executesqldatetimeitemnow
3条回答

如果您只是想获得完整的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`.

为了得到275,你只需要

print(values[1])

假设

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

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

相关问题 更多 >