I am trying to update a dictionary based on the time delta generated from its value.
This is an example of the dictionary:
my_dict = {'6.1.7.1': {'timestamp':('2020-05-26 12:05:08')}, '1.1.1.2': {'timestamp': ('2020-05-26 12:05:08')}, '2.61.5.4': {'timestamp': ('2020-05-25 12:05:08')},}
I want to find out if the key value has a timestamp value that exceeds 24hr to delete it, so I have done this:
from datetime import date from datetime import datetime import pandas as pd today = date.today() today=today.strftime(format= '%Y-%m-%d %H:%M:%S') today=pd.to_datetime(today) print( today) for k,v in my_dict.items(): timedelta = v - today if timedelta>24: my_dict.pop(k, None)
but I get the following error:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-49-037388a76b67> in <module> 8 9 for k,v in my_dict.items(): ---> 10 timedelta = v - today 11 if timedelta>24: 12 my_dict.pop(k, None) pandas/_libs/tslibs/timestamps.pyx in pandas._libs.tslibs.timestamps._Timestamp.__sub__() TypeError: descriptor '__sub__' requires a 'datetime.datetime' object but received a 'dict'
How can I manipulate the value of the dictionary to do get the timedelta and after eliminate the key and value in the dictionary? Any help will be appreciated since I am not very familiar with dictionaries.
Advertisement
Answer
If I understood you correctly, then this should works with you
# you can define a filter function which return a new dictionary def my_filter(my_dict): # define a new dict new_dict = dict({}) now = datetime.now() now=today.strftime(format= '%Y-%m-%d %H:%M:%S') now=pd.to_datetime(now) # loop on the old dictionary for (k, v) in my_dict.items(): # you have to get the 'timestamp' from each value and convert it to datetime timedelta = now - pd.to_datetime(v['timestamp']) # convert the timedelta to hours and check if it's less than 24 hours to add it to the new dict if (timedelta.days*24+timedelta.seconds/3600)<=24: new_dict[k] = v return new_dict