0

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)
Swain
  • 1
  • 1
  • 1
    You are sorting the ledger every time you add a date; instead, you could add all the dates, then sort the ledger once. Pushing on that idea; add all the dates as `datetime` objects to a temporary ledger; sort the temporary ledger; then `ledger = [raw_date.strftime('%w %b %y') for raw_date in temporary_ledger]` – Stef Oct 01 '20 at 11:16
  • Improving on that idea; you could create a class `Ledger` which maintains a sorted collection of `datetime` objects, with a method `Ledger.view()` that returns a list of strings. – Stef Oct 01 '20 at 11:21
  • Why don't you just keep the `raw_date` in your list and use `strftime` only for printing? – tobias_k Oct 01 '20 at 11:52
  • Thanks @Stef. I haven't tried this approach so thanks for mentioning. I can sort the datetime objects fine, but when I apply the date formatting change, the date sort becomes incorrect again. ``` ['2 Dec 21', '0 Nov 21', '5 Nov 21', '4 Nov 21', '1 Nov 21', '5 Oct 21', '5 Oct 21', '4 Oct 21', '0 Oct 21', '4 Oct 21'] ``` That's an example of the output. Also have 0 values, but will get to that layer – Swain Oct 01 '20 at 14:20
  • @Swain: if we ignore the dates with a 0, then your list appears to be sorted in reverse order. Try `.sort(reverse=True)` or `.sort(reverse=False)`. You might also find this answer interesting: [Generate a random date between two other dates](https://stackoverflow.com/a/553448/3080723) – Stef Oct 01 '20 at 17:12
  • Thanks @Stef, I see it's the 0s that are causing the issue now. Thanks for that link, it's really helped my thinking and I'm going to refine the date generator so it doesn't create these 0 dates – Swain Oct 02 '20 at 08:29
  • Finally figured out the 0 problem. I was passing the wrong directive to strftime. %w has a Sunday as 0. Got it working now, and reduced the amount code. Thanks for sticking with me @Stef! – Swain Oct 02 '20 at 12:08

1 Answers1

-1

here:

date = raw_date.strftime('%w %b %y') #Change format of date

you convert the datetime object to str. Try instead to skip this line and replace the last line in date_gen with ledger.sort()

Roei Levy
  • 21
  • 4