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???
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With