pythonpython-3.xpython-3.11

How to work with dates in dictionaries, if I want to compare and remove them?


I would like to write a small program that has a database of coupons and their expiration dates. I chose to store them in a dictionary format, where the key is the name of an item and the value is the expiration date.

coupons: dict = {'Rice':'2024-04-03',
                 'Caviar':'2024-04-05',
                 'Granola':'2024-08-10',
                 'Eggs':'2024-04-02'}

Within that, there is a function that goes through every item in the dictionary to check if the coupon is still good or not (date < today), and remove the coupon if it can no longer be used.

At first, I stored the dates in the datetime(2024,4,4) format in the dict itself, I could use that for comparison to check the number of expired ones in the list but otherwise returns the TypeError: 'datetime.datetime' object is not iterable when I want to remove it from the dictionary. So now I tried changing it to a string and use it that way. Here's what I have now:

def couponCheck(db: dict[str,str]) -> dict:
    expired: int = 0
    now: datetime = datetime.now()
    for i in db:
        b = time.strptime(db.get(i),'%Y-%m-%d')
        if b < now:
            expired += 1
            db.pop(i, None)
    if expired > 1:
        print(f'I found {expired} expired coupons in your catalog.')
    elif expired == 1:
        print('There was one expired coupon in your catalog.')
    else:
        print('I couldn\'t find any expired coupons. Yay!')

This results in the following error: TypeError: '<' not supported between instances of 'time.struct_time' and 'datetime.datetime'

How could I properly compare the two dates (now and the value) in a way that can also be removed from the dict by a fuction?


Solution

  • By storing your dates as strings in the form of YYYY-MM-DD you can perform lexical comparisons. In fact, that's precisely why that portable format is so widely used.

    Therefore, in this case you could do this:

    from datetime import datetime
    
    coupons: dict[str, str] = {
        "Rice": "2024-04-03",
        "Caviar": "2024-04-05",
        "Granola": "2024-08-10",
        "Eggs": "2024-04-02",
    }
    
    today = datetime.strftime(datetime.now(), "%Y-%m-%d")
    
    for k, v in coupons.copy().items():
        if v < today:
            del coupons[k]
    
    print(coupons)
    

    Output:

    {'Caviar': '2024-04-05', 'Granola': '2024-08-10'}