Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of date strings

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?

like image 720
user2480542 Avatar asked Jul 13 '13 06:07

user2480542


People also ask

How do I sort a list by date?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.

How do you sort Days in Python?

You can simply use an array of day string in the function, and then use the day week number to sort elements like a boss.

How do you sort a date in a DataFrame in Python?

One thing to notice here is our DataFrame gets sorted in ascending order of dates, to sort the DataFrame in descending order we can pass an additional parameter inside the sort_values() function that will set ascending value to False and will return the DataFrame in descending order.


2 Answers

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')) 
like image 63
amatellanes Avatar answered Oct 01 '22 20:10

amatellanes


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'] 
like image 33
TerryA Avatar answered Oct 01 '22 18:10

TerryA