按创建时间排序目录

时间:2014-09-09 18:12:57

标签: python

我使用ftplib登录到ftp目录,并使用以下内容列出了包含在内的目录:

  

ftp.retrlines( 'LIST')

这就是它在终端给我的东西:

enter image description here

此列表按字母顺序排列,但我想知道是否有任何方法可以按左侧给出的日期对其进行排序?

我希望能够从最新到最旧排序。

谢谢! :)

2 个答案:

答案 0 :(得分:2)

使用strptime()将日期字符串转换为日期时间对象then sort

d = datetime.strptime(date_string, '%m-%d-%y %I:%M%p')

答案 1 :(得分:2)

应该是这样的:

sorted = list()
dirs = ftp.retrlines('LIST')
times = list()
for dir in dirs:
    times.append(datetime.strptime(dir, '%m-%d-%y %I:%M%p'))
*sort times with some algorithm from python library* (pretty sure times.sort() should work but I cant say for sure
for i in range(0,len(times)):
    for dir in dirs:
        if dir.startswith(times[i]):
            sorted.append(dir)
            break

Celeo说的是对的,但只会给你没有目录的排序时间,这将给你们两个。