Python 如何对日期时间或日期对象列表进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14472795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:35:57  来源:igfitidea点击:

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

pythonlistdatesortingdatetime

提问by user_78361084

How do I sort a list of date and/or datetime objects? The accepted answer hereisn'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???

采纳答案by Volatility

You're getting Nonebecause 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 aagain.

你得到None,因为list.sort()它运行在原地,这意味着它不返回任何东西,但修改列表本身。您只需要调用a.sort()而无需a再次分配。

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.

有一个内置函数sorted(),它返回列表的排序版本 -a = sorted(a)也可以执行您想要的操作。