Baldrick
Baldrick

Reputation: 11002

Sorting a list of dates in Python

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?

Upvotes: 2

Views: 274

Answers (3)

gausszh
gausszh

Reputation: 15

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'

Upvotes: 1

Neel
Neel

Reputation: 21243

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

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121466

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

Upvotes: 7

Related Questions