Reputation: 83
I have the following list that contains dates (but not formatted as datetime, only strings):
MyList = ['25/4/2014', '2/12/2014', '15/7/2014']
I want to sort this list from earliest date to the latest date. I put together the following code:
MyList = ['25/4/2014', '2/12/2014', '15/7/2014']
MyList2 = []
for i in MyList:
MyList2.append(datetime.strptime(i, "%d/%m/%Y"))
SortedList = sorted(MyList2)
Result = []
for n in SortedList:
m = n.strftime('%d/%m/%Y')
Result.append(m)
print Result
The list gets sorted, but the problem is that the format is slightly different: ['25/04/2014', '15/07/2014', '02/12/2014']
Notice the extra "0" in the day and month numbers.
Is there any way to get the resulting list to have the original format where for example the month of April will be "4" and not "04"?
Thank you very much!
Upvotes: 2
Views: 1024
Reputation: 1121962
Use a key
function with sorted()
; this'll parse the dates just for sorting, leaving the original values untouched:
SortedList = sorted(MyList, key=lambda d: datetime.strptime(d, "%d/%m/%Y"))
The list is then sorted on the return values of the key
function instead of the values themselves. Internally, Python decorates the values (produces tuples of (key(v), None, v)
, with None
making sure v
is not involved in breaking ties), sorts these, then un-decorates again.
Demo:
>>> from datetime import datetime
>>> MyList = ['25/4/2014', '2/12/2014', '15/7/2014']
>>> sorted(MyList, key=lambda d: datetime.strptime(d, "%d/%m/%Y"))
['25/4/2014', '15/7/2014', '2/12/2014']
Upvotes: 4