Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort dates in python array

Tags:

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'] 
like image 344
Rajeev Avatar asked Mar 02 '11 11:03

Rajeev


People also ask

How do you sort an array of dates in Python?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.

How do you sort by month and year in Python?

The key is to turn your strings into something sortable and that's datetime objects ( datetime. strptime ) here. "%d/%b/%Y" is just format of your dates.

What is sort () in Python?

Python sorted() Function The sorted() function returns a sorted list of the specified iterable object. You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically. Note: You cannot sort a list that contains BOTH string values AND numeric values.


2 Answers

>>> 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'] 
like image 172
Tim Pietzcker Avatar answered Sep 18 '22 15:09

Tim Pietzcker


sorted(timestamps, key=lambda d: map(int, d.split('-'))) 
like image 32
jd. Avatar answered Sep 17 '22 15:09

jd.