按创建时间排序目录

2024-04-20 13:56:20 发布

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

我使用ftplib登录到一个ftp目录,并使用以下命令列出了其中包含的目录:

ftp.retrlines('LIST')

这就是它在终端给我的信息:

enter image description here

这张单子是按字母顺序排列的,但我想知道有没有办法按左边的日期对它进行排序?在

我想把它从最新的分类到最旧的。在

谢谢!:)


Tags: 命令目录信息终端排序字母分类ftp
2条回答

使用^{}将日期字符串转换为日期时间对象then sort。在

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

应该是这样的:

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说的是对的,但只会给你排序的时间,没有目录,这将给你两者。在

相关问题 更多 >