YosiFZ
YosiFZ

Reputation: 7900

Remove items from array when date passed

I have an array in my Python Project and I add items to the array with this code:

items.append({"date":time.time(), "item":item})

I want to remove all the items where the date passed after 10 seconds, I do it with this :

items = [item for item in items if item['date'] + 10 <= time.time()]

But this code removes all items and not the one that passed 10 seconds, any idea what is the problem?

Upvotes: 0

Views: 852

Answers (5)

Geofrey Asiimwe
Geofrey Asiimwe

Reputation: 212

You will need to use the timedelta object

from datetime import (
  datetime,
  timedelta
)
items.append({"date":datetime.now(), "item":item})
items = [item for item in items if item['date'] + timedelta(seconds=10) > datetime.now()]

Upvotes: 1

shahab-qazavi
shahab-qazavi

Reputation: 362

items = [item for item in items if item['date'] + timedelta(seconds=10) >= datetime.now()]

it worked for me and removed all items where the date passed after 10 seconds

Upvotes: -1

mtpelerin
mtpelerin

Reputation: 9

first you should use timedelta.

import datetime    

present = datetime.datetime.now()
past = present - datetime.timedelta(seconds=10)

then you can easly compare date with < >

for example:

for item in items:
    past = datetime.datetime.now() - datetime.timedelta(seconds=2)
    if item['date']<past:
        items.remove(item)

Upvotes: 0

RafalS
RafalS

Reputation: 6354

You should be checking if timepoint + 10 seconds is greater than current timepoint, because it means that 10 seconds haven't passed yet

items = [item for item in items if item['date'] + 10 > time.time()]

I would change the time logic to this to make it more clear:

items = [item for item in items if time.time() - item['date'] <= 10]

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

You want to remove items that are existing more than 10 second in the list, for that you should save the one that are less than 10, change your code to check the opposite.

items = [item for item in items if item['date'] + 10 > time.time()]

Upvotes: 1

Related Questions