1

I have a list of datetime with multiple [start time, end time] combination. How can I sort the list based on start time efficiently?

[
[datetime.datetime(2013, 1, 2, 14, 0), datetime.datetime(2013, 1, 2, 16, 0)],
[datetime.datetime(2013, 1, 1, 9, 0), datetime.datetime(2013, 1, 1, 10, 0)],                  
[datetime.datetime(2013, 1, 1, 12, 0), datetime.datetime(2013, 1, 1, 16, 0)], 
]

I knew that sorted() and attrgetter() works well for namedtuple list, but is there any sorting function which works for the above scenario?

1 Answer 1

6

sorted will work just fine. It should sort the inner lists lexicographically. Meaning, it'll first compare the first elements (starttime), then if those are the same, it'll compare the second elements (endtime).

>>> data
[[datetime.datetime(2013, 1, 2, 14, 0), datetime.datetime(2013, 1, 2, 16, 0)], [datetime.datetime(2013, 1, 1, 9, 0), datetime.datetime(2013, 1, 1, 10, 0)], [datetime.datetime(2013, 1, 1, 12, 0), datetime.datetime(2013, 1, 1, 16, 0)]]
>>> sorted(data)
[[datetime.datetime(2013, 1, 1, 9, 0), datetime.datetime(2013, 1, 1, 10, 0)], [datetime.datetime(2013, 1, 1, 12, 0), datetime.datetime(2013, 1, 1, 16, 0)], [datetime.datetime(2013, 1, 2, 14, 0), datetime.datetime(2013, 1, 2, 16, 0)]]

If you ever need it (and you probably will), you can specify a key function. Say you don't care at all about the endtime and only want to sort by starttime (preserving original order regardless of endtime if multiple records have the same starttime):

sorted(data, key=operator.itemgetter(0))

would do the trick.

Sign up to request clarification or add additional context in comments.

Comments

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.