sorteddictionary

Sorting dictionary by keys that are dates


When developing a telegram bot, you need to sort the dictionary by date, to output news in chronological order. The problem is the difference in key formats (dates). There is the format %d.%m at %H:M%, and there is %d.%m.%Y at %H:M%.

for k,v in sorted(Dnews_dict.items(), key=lambda x: DT.strptime(x[1].get("time"),'%d.%m.%Y at %H:%M')):
                news = f"<b>{v['time']}</b>\n"\
                f"{hlink(v['title'],v['url'])}"
                await message.answer(news)

This code works fine, but only with 1 date type. As an option, i tried to add a string length condition (length is constant).

if len(round_data) == 18:
            for k,v in sorted(Dnews_dict.items(), key=lambda x:DT.strptime(x[1].get("time"),'%d.%m.%Y в %H:%M')):
                news = f"<b>{v['time']}</b>\n"\
                f"{hlink(v['title'],v['url'])}"
                await message.answer(news)
else:
            for k,v in sorted(Dnews_dict.items(), key=lambda x:DT.strptime(x[1].get("time"),'%d.%m at %H:%M')):
                news = f"<b>{v['time']}</b>\n"\
                f"{hlink(v['title'],v['url'])}"
                await message.answer(news)

But the condition doesn’t work. But that condition doesn’t work. How can this dilemma be resolved? enter image description here


Solution

  • While I am unfamiliar with the telegraph bot, the following is a way to deal with datetime data having mixed formats e you have isolated the specific text containing the date time data:

    So given a list of mixed datetime string data of the following formats:

    datelist = ['08.02.2022 at 23:53',
     '13.07 at 18:13',
     '23.11.2022 at 19:55',
     '15.02 at 01:06',
     '09.07.2022 at 14:57',
     '09.08 at 04:06',
     '19.04.2022 at 07:19',
     '28.10 at 21:56',
     '19.10.2022 at 02:18',
     '23.04 at 18:15']  
    
        from dateutil import parser    #Utility for handling all the messy dates you encounter along the way
        from dateutil.relativedelta import *  
    
    for dt in datelist:
        print(parser.parse(dt))  
    

    Yields:

    2022-08-02 23:53:00
    2023-01-13 18:13:00
    2022-11-23 19:55:00
    2023-01-15 01:06:00
    2022-09-07 14:57:00
    2023-01-09 04:06:00
    2022-04-19 07:19:00
    2023-01-28 21:56:00
    2022-10-19 02:18:00
    2023-01-23 18:15:00  
    

    If the year 2023 is of concern, you can do the following:

    for dt in datelist:
        dtx = parser.parse(dt)
        if dtx.year == 2023:
            dtx = dtx + relativedelta(year=2022)
        print(dtx)  
    

    Which produces a result keyed to the year 2022:

    2022-08-02 23:53:00
    2022-01-13 18:13:00
    2022-11-23 19:55:00
    2022-01-15 01:06:00
    2022-09-07 14:57:00
    2022-01-09 04:06:00
    2022-04-19 07:19:00
    2022-01-28 21:56:00
    2022-10-19 02:18:00
    2022-01-23 18:15:00