The key is to find a suitable data structure which allows you to use the built-in sorted function directly.
For example, if your date strings were in YYYY-MM-DD format and your data was structured like this,
data = [
('2024-07-05', b'15-21-00', 0),
('2024-08-16', b'23-41-01', 1),
('2024-08-16', b'15-20-55', 2)
]
then you could use
sorted_indexes = [i for date, time, i in sorted(data)]
because sorted sorts lists of tuples lexicographically (i.e., first by date, then equal dates by time, and as a bonus, equal times by index).
Since you don't have this format and structure, you need to create it (temporarily).
You can use the datetime module to convert each date string:
from datetime import datetime
def convert_date(date):
"""Convert byte string in DD-MM-YYYY to Unicode string in YYYY-MM-DD format."""
return datetime.strptime(date.decode(), "%d-%m-%Y").strftime("%Y-%m-%d")
You can use a dictionary to combine the corresponding dates and times:
tmp = {}
for date, i in date_list:
tmp[i] = [convert_date(date)]
for time, i in time_list:
tmp[i].append(time) # assuming that i was already contained in date_list
data = [(date, time, i) for i, (date, time) in tmp.items()]
You can put everything in a function to keep it tidy:
def sort_dates_and_times(dates, times):
tmp = {}
for date, i in dates:
tmp[i] = [convert_date(date)]
for time, i in times:
tmp[i].append(time) # assuming that i was already contained in date_list
data = [(date, time, i) for i, (date, time) in tmp.items()]
return [i for date, time, i in sorted(data)]
sorted_indexes = sort_dates_and_times(date_list, time_list)
Another suitable data structure would be
data = {
0: ('2024-07-05', b'15-21-00'),
1: ('2024-08-16', b'23-41-01'),
2: ('2024-08-16', b'15-20-55')
}
which incidentally already exists as tmp above.
(The difference between tuples and lists as values doesn't matter now.)
Then instead of post-processing the output of sorted to get the indexes,
data = [(date, time, i) for i, (date, time) in tmp.items()]
return [i for date, time, i in sorted(data)]
you would use a key argument to specify to sort the indexes not by the indexes but by the corresponding dates and times:
def date_time_of_index(i):
return tmp[i]
return sorted(tmp, key=date_time_of_index)
Or more succinctly:
return sorted(tmp, key=lambda i: tmp[i])
Or even more succinctly (as suggested by no comment in a comment):
return sorted(tmp, key=tmp.get)