How do I sort a list of datetime or date objects?

PythonListDateSortingDatetime

Python Problem Overview


How do I sort a list of date and/or datetime objects? The accepted answer here isn't working for me:

from datetime import datetime,date,timedelta


a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)]
print a # prints '[datetime.date(2013, 1, 22), datetime.date(2013, 1, 23), datetime.date(2013, 1, 21)]'
a = a.sort()
print a # prints 'None'....what???

Python Solutions


Solution 1 - Python

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser_78361084View Question on Stackoverflow
Solution 1 - PythonVolatilityView Answer on Stackoverflow