Sort list of date strings
Try this:
import datetime
d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
Use sorted()
with a key:
>>> d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007']
>>> def sorting(L):
... splitup = L.split('-')
... return splitup[1], splitup[0]
...
>>> sorted(d, key=sorting)
['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']
It's better to use a function here instead of a lambda to prevent calling split()
twice (and it looks a bit neater :))
Note that this will return the sorted list. If you want to sort it in place, use .sort()
:
>>> d.sort(key=sorting)
>>> d
['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013']