nlhenderson17
nlhenderson17

Reputation: 87

Python: sort by date and time?

I have a list of objects that each contain a datetime.date() and a datetime.time() element. I know how to sort the array based on a single element using insertion sort, or any other sorting algorithm. However, how would I sort this list in chronological order using date AND time?

Upvotes: 0

Views: 904

Answers (1)

Steve Jessop
Steve Jessop

Reputation: 279245

Use a tuple of (my_date, my_time) as the "single element" you're sorting on. You could build a datetime.datetime object from the two, but that seems unnecessary just to sort them.

This applies in general to any situation where you want a lexicographical comparison between multiple quantities. "Lexicographical" meaning, most-significant first with less-significant quantities as tie-breakers, which is exactly what the standard comparisons do for tuple.

Upvotes: 2

Related Questions