如何在python中编写比较器函数来对日期进行排序

时间:2016-11-08 00:13:13

标签: python

我想写一个比较器函数来对以下日期列表进行排序

timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']

怎么做?

更新:

我有这个:timestamps.sort(key=lambda x: time.mktime(time.strptime(x,"%Y-%m-%d")))

但我想写一个比较器函数。

3 个答案:

答案 0 :(得分:0)

这可能不是这样做的方法,即使它产生了正确的结果..

timestamps.sort(key=lambda d:"%d%02d%02d"%tuple(map(int,d.split('-'))))

答案 1 :(得分:0)

以下是其中一种方法:

from datetime import datetime

timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']

converted_timestamps = [datetime.strptime(x, '%Y-%m-%d') for x in timestamps] 
sorted_timestamps = sorted(converted_timestamps)
sorted_timestamps_as_string = [datetime.strftime(date, "%Y-%m-%d") for date in sorted_timestamps]
print(sorted_timestamps_as_string)

输出:

  

$ python tes.py

     

['2010-01-12','2010-01-14','2010-02-07',   '2010-02-11','2010-11-16','2010-11-22','2010-11-23','2010-11-26',   '2010-12-02','2010-12-13','2011-02-04','2011-06-02','2011-08-05',   '2011-11-30']

我觉得它更具可读性。

答案 2 :(得分:0)

一种简单的方法。转换为datetime对象,排序,然后转换回字符串。

from datetime import datetime
def sort_dates(string_dates):
    dates = [datetime.strptime(string_date, "%Y-%m-%d") for string_date in string_dates]
    dates.sort()
    return [datetime.strftime(date, "%Y-%m-%d") for date in dates]

示例输出:

>>> print sort_dates(['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16'])
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-11-16', '2010-11-22', '2010-11-23', '2010-11-26', '2010-12-02', '2010-12-13', '2011-02-04', '2011-06-02', '2011-08-05', '2011-11-30']