我有一个存储在datetime
个对象中的生日列表。如何仅使用month
和day
参数在Python中对这些进行排序?
例如,
[
datetime.datetime(1983, 1, 1, 0, 0)
datetime.datetime(1996, 1, 13, 0 ,0)
datetime.datetime(1976, 2, 6, 0, 0)
...
]
谢谢! :)
答案 0 :(得分:13)
您可以使用month
和day
创建可用于排序的值:
birthdays.sort(key = lambda d: (d.month, d.day))
答案 1 :(得分:7)
l.sort(key = lambda x: x.timetuple()[1:3])
答案 2 :(得分:3)
如果日期存储为字符串 - 你说它们不是,虽然看起来像是 - 你可以使用dateutil的解析器:
>>> from dateutil.parser import parse
>>> from pprint import pprint
>>> bd = ['February 6, 1976','January 13, 1996','January 1, 1983']
>>> bd = [parse(i) for i in bd]
>>> pprint(bd)
[datetime.datetime(1976, 2, 6, 0, 0),
datetime.datetime(1996, 1, 13, 0, 0),
datetime.datetime(1983, 1, 1, 0, 0)]
>>> bd.sort(key = lambda d: (d.month, d.day)) # from sth's answer
>>> pprint(bd)
[datetime.datetime(1983, 1, 1, 0, 0),
datetime.datetime(1996, 1, 13, 0, 0),
datetime.datetime(1976, 2, 6, 0, 0)]
如果你的日期采用不同的格式,你可能会模糊解析一下:
>>> bd = [parse(i,fuzzy=True) for i in bd] # replace line 4 above with this line