Sort a list of dates by month in python [duplicate]

大憨熊 提交于 2020-06-13 12:18:11

问题


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


回答1:


Try sorted with key.

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



回答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.



来源:https://stackoverflow.com/questions/32290801/sort-a-list-of-dates-by-month-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!