Sorting dates in Python

I am storing the day and time of some scheduled tasks in txt in this format:

Monday,10:50-11:32

Friday,18:33-18:45

Sunday,17:10-17:31

Sunday,14:10-15:11

Friday,21:10-23:11

      

I open txt and get the content in the list. How can I sort the list to arrange the days and dates? Like this:

Monday,10:50-11:32

Friday,18:33-18:45

Friday,21:10-23:11

Sunday,14:10-15:11

Sunday,17:10-17:31

      

+3


source to share


1 answer


Okay, let's say you only have daylight and timestamps. One option is to calculate the number of minutes each item has been in (Monday 00:00 = 0 minutes and Sunday 23:59 = maximum minutes) and sort with this function.

The example below is sorted with the first timestamp value. One comment from an SO partner: er pointed out that this does not include the second timestamp (end time). To enable this, we can add a decimal value by inverting the number of minutes per day.

((int(h2)* 60 + int(m2))/24*60) # minutes divided by maximum minutes per day gives a decimal number

      

However, the key here is the following code:

weekday[day]*24*60 + int(h1)*60 + int(m1) # gets the total minutes passed, we sort with this!

      

And of course there is a sorting function with a link (double line). When you pass a key to sorted () and that key is a function, the sort will be based on the return values โ€‹โ€‹of that function (which is the number of minutes).



'\n\n'.join(sorted(list_, key=get_min))

      

Enough text ... let's move on to the complete example of the updated version

import io

file= """Monday,10:50-11:32

Friday,18:33-18:45

Sunday,17:10-17:31

Sunday,17:10-15:11

Friday,21:10-23:11"""

list_ = [i.strip('\n') for i in io.StringIO(file).readlines() if i != "\n"]

weekday = dict(zip(["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],[0,1,2,3,4,5,6]))

def get_min(time_str):
    day,time = time_str.split(",")
    h1, m1 = time.split('-')[0].split(":")
    h2, m2 = time.split('-')[1].split(":")
    return weekday[day]*24*60 + int(h1)*60 + int(m1) + ((int(h2)* 60 + int(m2))/24*60)

with open("output.txt", "w") as outfile:
    outfile.write('\n\n'.join(sorted(list_, key=get_min)))
    print('\n\n'.join(sorted(list_, key=get_min)))

      

Creates "output.txt" with:

Monday,10:50-11:32

Friday,18:33-18:45

Friday,21:10-23:11

Sunday,17:10-15:11

Sunday,17:10-17:31

      

+4


source







All Articles