在Python中排序日期列表 [英] Sorting a list of dates in Python
本文介绍了在Python中排序日期列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在python中列出了一个列表,名称是创建日期的目录;
I have a list in python that is directories who's names are the date they were created;
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']
我想要最新的目录是例如 01-03-2014
,第二个列表。日期是DD-MM-YYYY。
I want the most recent directory which is that example is 01-03-2014
, the second in the list. The dates are DD-MM-YYYY.
可以使用lamba排序键排序,还是应该简单地点击并写一个简单的排序函数?
Can this be sorted using the lamba sort key or should I just take the plunge and write a simple sort function?
推荐答案
您可以在排序键中解析日期:
You'd parse the date in a sorting key:
from datetime import datetime
sorted(ConfigList, key=lambda d: datetime.strptime(d, '%d-%m-%Y'))
演示:
>>> 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']
这篇关于在Python中排序日期列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文