Home > Software engineering >  Python - order python list by datetime object
Python - order python list by datetime object

Time:03-06

I have a list of datetime objects that's being appended into an array from my database with an additional library called Django Recurrence.

I append it as follows inside a for loop:

events = Events.objects.filter(...some conditions)
timeslots = []
for event in events:
    for occurence in event.recurrences.between(context['today'], context['end']):
    occurence_date = datetime.combine(occurence.date(), time(0, 0))
    timeslots.append({
                        'start_date': occurence_date   timedelta(hours=event.start_time.hour, minutes=event.start_time.minute),
                        'end_date': occurence_date   timedelta(hours=event.end_time.hour, minutes=event.end_time.minute),
                    })

It would then output it as [{'start_date': datetime.datetime(2022, 3, 7, 14, 0), 'end_date': datetime.datetime(2022, 3, 7, 15, 0)}, {'start_date': datetime.datetime(2022, 3, 8, 14, 0), ... }] which is great.

A side effect from the events loop, is that it would add a the other events, after all the occurrences, eg 1 march, 5 march, 10 march, 2 march, 4 march, etc etc etc. I'd like to order them by the starting date, so I can render them out in the correct order in my template.

Thanks

CodePudding user response:

If you want to sort a list of dictionaries, you can use sorted,

but you have to pass the key you want to sort with, something like this:

 sorted_timeslots = sorted(timeslots, key=lambda x: x['start_date'])

CodePudding user response:

You can try sorted which takes two arguments: An iterable object, and a key. The latter indicates how the function should sort the former argument(array). I have generated an example to be more explicit:

timeslots  = [{'start_date': datetime.datetime(2022, 3, 7, 14, 0), 'end_date': datetime.datetime(2022, 3, 7, 15, 0)}, 
              {'start_date': datetime.datetime(2022, 3, 8, 14, 0) ,'end_date': datetime.datetime(2022, 3, 5, 14, 0)}, 
              {'start_date': datetime.datetime(2022, 3, 10, 20, 0) ,'end_date': datetime.datetime(2022, 3, 7, 13, 0)},
              {'start_date': datetime.datetime(2022, 3, 3, 20, 0) ,'end_date': datetime.datetime(2022, 3, 7, 11, 0)}
             ]
sorted(timeslots, key=lambda x: x["start_date"])

Output

[{'end_date': datetime.datetime(2022, 3, 7, 11, 0),
  'start_date': datetime.datetime(2022, 3, 3, 20, 0)},
 {'end_date': datetime.datetime(2022, 3, 7, 15, 0),
  'start_date': datetime.datetime(2022, 3, 7, 14, 0)},
 {'end_date': datetime.datetime(2022, 3, 5, 14, 0),
  'start_date': datetime.datetime(2022, 3, 8, 14, 0)},
 {'end_date': datetime.datetime(2022, 3, 7, 13, 0),
  'start_date': datetime.datetime(2022, 3, 10, 20, 0)}]
  • Related