0

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

NachoMiguel
  • 983
  • 2
  • 15
  • 29

2 Answers2

3

Try sorted with key.

from datetime import datetime
days_sorted = sorted(days, key=lambda day: datetime.strptime(day, "%d/%b/%Y"))
beezz
  • 2,398
  • 19
  • 15
  • perfect, thanks. Can i ask u to explain to me how exactly this works?. I will mark it as correct in 5 minutes. – NachoMiguel Aug 29 '15 at 21:47
  • The key is to turn your strings into something sortable and that's `datetime` objects (`datetime.strptime`) here. `"%d/%b/%Y"` is just [format of your dates](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior). – beezz Aug 29 '15 at 21:54
2

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.

JHobern
  • 866
  • 1
  • 13
  • 20