2

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']

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.

Can this be sorted using the lamba sort key or should I just take the plunge and write a simple sort function?

1
  • 1
    You can always use a sort key. That is entirely independent of the sort function or algorithm Commented Apr 8, 2014 at 8:24

3 Answers 3

7

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']
Sign up to request clarification or add additional context in comments.

1 Comment

+1. Apart from the first line, I had the exact same answer, word for word. Too fast man, I'm only on a mobile device atm :).
1

sorted will return copy of original list.

If you want to sort data in same object, you can sort using list.sort method.

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']

Comments

1

you want the most recent directory. so max function

import datetime
ConfigList = ['01-02-2014', '01-03-2014', '01-08-2013', '01-09-2013', '01-10-2013']
max(ConfigList,key=lambda d:datetime.datetime.strptime(d, '%d-%m-%Y'))
# output '01-03-2014'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.