I'm generating a list of random dates using Datetime and need to display as dd/mm/yy (eg 24 March 20 is 24/03/20). I can get this sorted with strftime, however it breaks the sort as it goes left to right so it's taking the day and sorting in that order.
It seems like overkill to get a datetime object, convert into a string for formatting, then convert that string back into a datetime object to sort.
How can I sort this list for dates correctly?
Thanking you in advance!
import random
from datetime import datetime, timedelta
user_test_date = datetime.strptime("12/12/21", '%d/%m/%y')
ledger = []
''' Create date for transaction '''
def date_gen():
date_step = random.randrange(1, 60) # Set range of 2 months
raw_date = user_test_date + timedelta(days =- date_step) # Alter days value each loop
date = raw_date.strftime('%w %b %y') #Change format of date
ledger.append(date)
ledger.sort(key=lambda item: item[0], reverse=True) #Sort list of dates
for i in range(10):
date_gen()
print(ledger)