[英]Sorting a list of dates in Python
I have a list in python that is directories who's names are the date they were created; 我在python中有一个列表,它是名称是创建日期的目录;
import os
ConfigDir = "C:/Config-Archive/"
for root, dirs, files in os.walk(ConfigDir):
if len(dirs) == 0: # This directory has no subfolder
ConfigListDir = root + "/../" # Step back up one directory
ConfigList = os.listdir(ConfigListDir)
print(ConfigList)
['01-02-2014', '01-03-2014', '01-08-2013', '01-09-2013', '01-10-2013']
I want the most recent directory which is that example is 01-03-2014
, the second in the list. 我想要最新的目录,即该示例是01-03-2014
,列表中的第二个。 The dates are DD-MM-YYYY. 日期是DD-MM-YYYY。
Can this be sorted using the lamba sort key or should I just take the plunge and write a simple sort function? 可以使用lamba排序键对其进行排序,还是应该进行简单的排序并编写一个简单的排序函数?
You'd parse the date in a sorting key: 您将在排序键中解析日期:
from datetime import datetime
sorted(ConfigList, key=lambda d: datetime.strptime(d, '%d-%m-%Y'))
Demo: 演示:
>>> from datetime import datetime
>>> ConfigList = ['01-02-2014', '01-03-2014', '01-08-2013', '01-09-2013', '01-10-2013']
>>> sorted(ConfigList, key=lambda d: datetime.strptime(d, '%d-%m-%Y'))
['01-08-2013', '01-09-2013', '01-10-2013', '01-02-2014', '01-03-2014']
sorted
will return copy of original list. sorted
将返回原始列表的副本。
If you want to sort data in same object, you can sort using list.sort
method. 如果要对同一对象中的数据进行排序,可以使用list.sort
方法进行排序。
In [1]: from datetime import datetime
In [2]: ConfigList = ['01-02-2014', '01-03-2014', '01-08-2013', '01-09-2013', '01-10-2013']
In [3]: ConfigList.sort(key=lambda d: datetime.strptime(d, '%d-%m-%Y'))
In [4]: ConfigList
Out[4]: ['01-08-2013', '01-09-2013', '01-10-2013', '01-02-2014', '01-03-2014']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.