简体   繁体   中英

'datetime.datetime' object is not subscriptable

I've checked every other post about this, but none can fix my issue.

I made a list that holds tuples with an id and a datetime object. Everytime I try to clean up the list with: last_encounters = [item for item in last_encounters if item[1] < datetime.utcnow] I get the error that 'datetime.datetime' object is not subscriptable . It's getting pretty annoying, I tried dicts.. didn't work.

Also tested the item[1], according to my print it is a datetime.

Even tried changing it to (x,y) for x,y in last_encounters if y < ... also did NOT work.

Some useful code:

list = []
d_t = datetime.utcfromtimestamp(9000000)     
list += [('lel', d_t)]     
list = [item for item in list if item[1] < datetime.utcnow]

I hope someone can tell me what I am doing wrong here.

Thanks in advance,

Kevin

When you do last_encounters += (a, b) , you are adding two sequences together, last_encounters and (a,b) . This means you end up with a and b stuck on the end of the list, rather than just adding the tuple to the list.

There are two options to fix your problem:

  1. Add a sequence containing your tuple:

      last_encounters += [(d["id"], d["d_t"])] 
  2. Or preferably, use the append method:

      last_encounters.append((d["id"], d["d_t"])) 

It looks like your problem is the way you add the tuple to the list. Here is an example to show the problem :

l = []
l += ("a", "b")
print l

l = []
l.append( ("a", "b"))
print l  

Which gives :

>>> ['a', 'b']
>>> [('a', 'b')]

So list+=tuple is equivalent to calling list.extend(tuple) and not list.append(tuple) which is what you want.

A side note on the meaning of the exception that was raised : X is not subscriptable means that your are trying to call that syntax X[some int] while the object doesn't support it.

Try calling utcnow as a method utcnow() :

last_encounters = [item for item in last_encounters if item[1] < datetime.utcnow()]

I couldn't reproduce your error with a version of your code, but a version with items in the list lead to this fix.

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