Sort list of date strings

Question:

I have an arbitrary list of date strings (mm-yyyy) as follows:

d = ['09-2012', '04-2007', '11-2012', '05-2013', '12-2006', '05-2006', '08-2007'...]

I need this list to be sorted first by the level of years (ascending), then on the level of months (ascending)..so that the logical ordering can be:

d_ordered = ['05-2006', '12-2006', '04-2007', '08-2007', '09-2012', '11-2012', '05-2013' ...]

How can I achieve this?

Asked By: user2480542

||

Answers:

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']
Answered By: TerryA

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'))
Answered By: amatellanes
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.