Somethingwhatever
Somethingwhatever

Reputation: 1348

Filter dictionary based on date in python?

I have a dictionary that looks like this and the dates are in string format :-

{ "2021-04-21" : "Shoes",
  "2021-04-07" : "Clothes"
  "2021-03-19" : "Chocolates"
  "2021-03-12" : "Flowers",
  "2021-03-03" : "Gloves" }

And the way i am creating my dict is through a list :-

my_order_dictionary = {s[:10]: s[10:] for s in output[1:]}

I am trying to get the values for dates older than 30 days ago from the present day, So i did :-

d = datetime.today() - timedelta(days=30)
for key,value in my_order_dictionary.items():
    if (key < d):
        print(value)

But i get the following error :-

    if (key < d):
TypeError: '<' not supported between instances of 'str' and 'datetime.datetime'

How can i fix the data types and then filter based on date?

Upvotes: 0

Views: 1175

Answers (4)

Alex G
Alex G

Reputation: 703

You have to cast the datetime (given as string) to a python datetime object for comparison with d. You can do it by datetime's strptime method. You have to change your if-statement to get the desired behavior.

if (datetime.strptime(key, '%Y-%m-%d') < d):

Upvotes: 1

Prune
Prune

Reputation: 77857

key is a string; d is a datetime. You have to convert your string dates to datetime. You have a consistent format; I expect that you can handle the conversion with what you already know, yes?

For instance:

my_order_dictionary = {datetime.strptime(s[:10], "%y-%m-%d")): s[10:]
                       for s in output[1:]}

Upvotes: 0

Barmar
Barmar

Reputation: 781096

You can format d into a string so you can compare it with the dictionary keys.

d = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d')

Upvotes: 2

12944qwerty
12944qwerty

Reputation: 1925

This is because key is a str value.

According to your dictionary initialization, each key is a string. And because your looping through each key of the dictionary, the key variable is also a string. You cannot compare a string with a DateTime object.

You can just use datetime.strptime() to convert the string into a datetime object.

Upvotes: 1

Related Questions