Warm tip: This article is reproduced from serverfault.com, please click

python function. output a keys list from a dictionary if the key is todays date

发布于 2020-11-27 23:55:54

i import datetime module. but i'm not sure how to call it as a dictionary key.

def bad_food():
    today = datetime.date.today()
    past_due = {
        datetime.date.today(2020,11,24): ['chicken' , 'soup', 'chips'],
        datetime.date.today(2020,11,27) : ['lays', 'chilli'],
                }
    for key in past_due:
        if key == today:
            print (today.values())
print(bad_food())```
Questioner
Dane Cantrell
Viewed
11
Sash Sinha 2020-11-28 08:17:04

You could compare a tuple of the info you have provided for each key i.e., the year, month and date with the same subset of available info from today:

>>> import datetime
>>>
>>> def bad_food():
...     today = datetime.datetime.now()
...     past_due = {
...         datetime.datetime(2020, 11, 24): ['chicken', 'soup', 'chips'],
...         datetime.datetime(2020, 11, 27): ['lays', 'chilli'],
...     }
...     for key in past_due:
...         if (key.year, key.month, key.day) == (today.year, today.month, today.day):
...             print(past_due[key])
...
>>> bad_food()
['lays', 'chilli']