如何用python编写一个comparator函数来排序日期

2024-06-14 23:16:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想编写一个comparator函数来对下面的日期列表进行排序

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")))

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


Tags: lambdakey函数列表time排序sorttimestamps
3条回答

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

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

以下是其中一种方法:

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']

我觉得它更有可读性。在

一个简单的方法接近它。转换为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]

样本输出:

^{pr2}$

相关问题 更多 >