Sorting a list of dates in Python
Question: 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?


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

