sort dates in python array
How to sort the below array of dates on python 2.4
timestamps = ['2011-06-2', '2011-08-05', '2011-02-04', '2010-1-14', '2010-12-13', '2010-1-12', '2010-2-11', '2010-2-07', '2010-12-02', '2011-11-30', '2010-11-26', '2010-11-23', '2010-11-22', '2010-11-16']
>>> import datetime
>>> dates = [datetime.datetime.strptime(ts, "%Y-%m-%d") for ts in timestamps]
>>> dates.sort()
>>> sorteddates = [datetime.datetime.strftime(ts, "%Y-%m-%d") for ts in dates]
>>> sorteddates
['2010-01-12', '2010-01-14', '2010-02-07', '2010-02-11', '2010-11-16', '2010-11-
22', '2010-11-23', '2010-11-26', '2010-12-02', '2010-12-13', '2011-02-04', '2011
-06-02', '2011-08-05', '2011-11-30']
sorted(timestamps, key=lambda d: map(int, d.split('-')))
Just doing that:
timestamps.sort()
result:
['2010-1-12',
'2010-1-14',
'2010-11-16',
'2010-11-22',
'2010-11-23',
'2010-11-26',
'2010-12-02',
'2010-12-13',
'2010-2-07',
'2010-2-11',
'2011-02-04',
'2011-06-2',
'2011-08-05',
'2011-11-30']
The order year-month-day allow such a sorting because a day changes before a month and a month changes before a year when time is passing.
It's like for a number: the unity digit (the rightmost digit) changes before the ten digit, and this latter changes before the hundred digit, when 1 is progressively added.
And there is the fact that sort() processes from left to right : if the characters at one precise position are the same in two strings to sort, it will examine the two characters in the two string at the following position to decide which one is logically preceding.
Plus the fact that '0' < '1' is True, '1' < '2' is True etc