Sort a list of dates by month in python

Question:

I have a list like this:

['25/May/2015', '27/May/2015', '27/Apr/2015', '27/Jan/2015', '07/May/2015' '22/May/2015', '16/Jan/2015', '29/Jan/2015', '28/Feb/2015', '18/Feb/2015', '08/May/2015', '20/Jan/2015', '24/Jan/2015', '31/Mar/2015', '30/Apr/2015', '17/Feb/2015', '19/Mar/2015', '05/May/2015', '22/Jan/2015', '14/Aug/2015', '26/Feb/2015', '14/Mar/2015', '28/May/2015']']

I want to order the dates by month: jan, feb, march, etc…
but also i want to order them by day, this means the first day must be: 1/jan/2015 then 2/jan/2015

i tried to sort the list:

days.sort()

BUT it´s ordering the list by days and not by months.

Any will be really appreciated

Asked By: NachoMiguel

||

Answers:

Try sorted with key.

from datetime import datetime
days_sorted = sorted(days, key=lambda day: datetime.strptime(day, "%d/%b/%Y"))
Answered By: beezz

You are going to want to sort the dates by using your own comparison function. sort allows this, you just need to say list.sort(key=comparison_function). To make a function to compare the months in your list, one simple idea I came up with was

months = {"Jan":0, "Feb":1, "Mar":2, "Apr":3, "May":4, "Jun":5, "Jul":6, "Aug":7, "Sep":8, "Oct":9, "Nov":10, "Dec":11 }

Make a dict that turns each month into a corresponding number

def month_value(date):
    return months[date.split('/')[1]]

Write a function that takes one of your strings and returns the value of the second component of it.

dates.sort(key=month_value)

This will sort the dates in place, according to their month.

Answered By: JHobern
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.