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
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:
Yields:
If the year 2023 is of concern, you can do the following:
Which produces a result keyed to the year 2022: