Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I sort a list of datetime or date objects?

How do I sort a list of date and/or datetime objects? The accepted answer here isn't working for me:

from datetime import datetime,date,timedelta   a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)] print a # prints '[datetime.date(2013, 1, 22), datetime.date(2013, 1, 23), datetime.date(2013, 1, 21)]' a = a.sort() print a # prints 'None'....what??? 
like image 653
user_78361084 Avatar asked Jan 23 '13 05:01

user_78361084


People also ask

How do I sort datetime objects?

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.

Can you sort a list of objects in Python?

A simple solution is to use the list. sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort. It accepts two optional keyword-only arguments: key and reverse.

How do you sort data by date in Python?

Python. We will be using the sort_values() method to sort our dataset and the attribute that we will pass inside the function is the column name using which we want to sort our DataFrame.


1 Answers

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

like image 88
Volatility Avatar answered Oct 18 '22 07:10

Volatility