3

I am saving the day and time period of some scheduled tasks in a 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 am opening the txt and get the contents in a list. How can I sort the list to get the days and the time periods in order? 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
  • Convert to a datetime object using datetime.strptime. Then you can use standard comparisons, e.g. those used by sorted(). Commented Jul 30, 2017 at 15:24
  • stackoverflow.com/questions/5166842/sort-dates-in-python-array Commented Jul 30, 2017 at 15:29
  • 2
    These dates are ambiguous what week they are. You should save your dates in a different format. Don't confuse the way you want to present the date and the unambiguous representation of a date and time. It will make tasks like this far easier if you store that date ISO 8601 format and they change the format to this once your read the file. Commented Jul 30, 2017 at 16:07

1 Answer 1

4

Ok let's say you only have dayofweek and the timestamps. One alternative is to calculate the amount of minutes each item is (Monday 00:00 = 0 minutes and Sunday 23:59 = max minutes) and sort with that function.

The example below sorts with the first timestamp value. One comment from a fellow SO:er pointed out that this does not include the second timestamp (end-time). To include this we can add a decimal value by inverting the amount 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 the sort function with a join (double-break line). When you pass a key to sorted() and that key is a function the sorting will be based on the return values of that function (which is the amount of minutes).

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

Enough text... let's jump to a full example 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
Sign up to request clarification or add additional context in comments.

2 Comments

Instead of key=lambda x: get_min(x) just write key=get_min
your get_min won't sort 'Monday,09:50-11:32' and 'Monday,09:50-11:30'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.