2

I am logged into an ftp directory using ftplib and have listed the directories contained inside using:

ftp.retrlines('LIST')

This is what it gives me in the terminal:

enter image description here

This list is in alphabetical order but i was wondering if there is any way to sort it by the dates given on the left?

I want to be able to sort it from newest to oldest.

Thanks! :)

user2804628
  • 133
  • 1
  • 13

2 Answers2

2

Use strptime() to turn the date strings into datetime objects, then sort.

d = datetime.strptime(date_string, '%m-%d-%y %I:%M%p')
Community
  • 1
  • 1
Celeo
  • 5,583
  • 8
  • 39
  • 41
2

Should be something like this:

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

What Celeo said is right but will only give you the sorted times without the directories, this will give you both.

tomer.z
  • 1,033
  • 1
  • 10
  • 25