How do I sort a list of datetime or date objects?
184,348
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.
Author by
user_78361084
Updated on October 22, 2020Comments
-
user_78361084 over 3 years
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???
-
radtek about 10 yearswhich way is best? do they do same things under the covers?
-
flyman over 9 years@radtek
list.sort()
changes the object from which it is invoked (which is always a list).sorted()
works on any iterable, not only list.list.sort()
might be a little faster if you have a very large list becausesorted()
creates a new list and needs to copy the elements to it.