Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/google-maps/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用python编写比较器函数对日期进行排序_Python - Fatal编程技术网

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

如何用python编写比较器函数对日期进行排序,python,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'] 怎么做 更新: 我有:ti

我想写一个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.strtime(x,“%Y-%m-%d”))


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

这可能不是实现它的方法,即使它产生了正确的结果

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]
样本输出:

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

这些是字符串,不是日期。先把它们转换成日期,然后按常规方式排序。你自己做过任何努力吗?如果是这样,如果您与他人分享,可能会有人提供帮助。Python不赞成使用
cmp
参数进行
sort
,而赞成使用
key
。为什么要编写比较器函数?@dan04,因为我不想使用任何内置模块。