【问题标题】:Python TypeError: 'datetime.datetime' object is not subscriptablePython TypeError:'datetime.datetime'对象不可下标
【发布时间】:2015-09-25 16:40:10
【问题描述】:

我在 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' 对象不可下标

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

【问题讨论】:

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

标签: python datetime


【解决方案1】:

如果您只是想获取完整的 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() ,那么您将得到一个元组列表,在这种情况下,您也可以遍历 list ,一次取一个元组,并获取索引处的元素1。示例 -

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      要获得 275,您只需要

      print(values[1])
      

      假设

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-14
        • 2023-03-20
        • 2015-07-31
        • 2020-02-23
        • 1970-01-01
        相关资源
        最近更新 更多