我需要按日期排序列表的python列表

时间:2013-06-18 12:45:15

标签: python sorting datetime

我需要按日期对列表进行排序:

mylist=['ML-M01 Qual Report 07/31/13', 'ML36220010 Complete Qual Testing 07/24/13', 'ML36220045 Final FRB 07/13/13', 'ML9822D2600 Brief to PM 08/5/13']

从这个网站,我得到了这个代码:

sorted(mylist, key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))

然而,我收到此错误消息:

sorted(mylist,key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    sorted(mylist,key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
  File "<pyshell#25>", line 1, in <lambda>
  sorted(mylist,key=lambda x: datetime.datetime.strptime(x[2], '%m/%d/%y'))
  File "C:\Python25\Lib\_strptime.py", line 330, in strptime
    (data_string, format))
ValueError: time data did not match format:  data=-  fmt=%m/%d/%y

需要帮助 - 需要按3d元素对列表进行排序 - 从最旧到最新

2 个答案:

答案 0 :(得分:8)

列表中的每个条目都是字符串,而不是列表,因此x[2]是单个字符(第一个条目为'-')。您需要将日期部分拆分为strptime()

sorted(mylist, key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))

str.rsplit()分隔空格,一次,以提高效率:

>>> 'ML-M01 Qual Report 07/31/13'.rsplit(None, 1)
['ML-M01 Qual Report', '07/31/13']
>>> 'ML-M01 Qual Report 07/31/13'.rsplit(None, 1)[-1]
'07/31/13'

结果:

>>> sorted(mylist, key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))
['ML36220045 Final FRB 07/13/13', 'ML36220010 Complete Qual Testing 07/24/13', 'ML-M01 Qual Report 07/31/13', 'ML9822D2600 Brief to PM 08/5/13']

请注意sorted()返回一个新的排序列表,原始列表不受影响。如果您想对mylist进行排序,请调用list.sort()方法:

mylist.sort(key=lambda x: datetime.datetime.strptime(x.rsplit(None, 1)[-1], '%m/%d/%y'))

答案 1 :(得分:2)

您的错误:

ValueError: time data did not match format:  data=-  fmt=%m/%d/%y

表示您获得的数据"-"不是日期。这表示您的列表中的行不会包含有效日期。

此解决方案通过返回None来处理无效日期。这将把所有无效日期放在一起:

import datetime

mylist=['ML-M01 Qual Report 07/31/13', 'ML36220010 Complete Qual Testing 07/24/13', 'ML36220045 Final FRB 07/13/13', 'ML9822D2600 Brief to PM 08/5/13']

def extract_date(text):
    try:
        return datetime.datetime.strptime(text.rsplit(None, 1)[-1], '%m/%d/%y')
    except ValueError:
        return None

mylist.sort(key=extract_date)

print mylist

输出:

['ML36220045 Final FRB 07/13/13', 
 'ML36220010 Complete Qual Testing 07/24/13', 
 'ML-M01 Qual Report 07/31/13', 
 'ML9822D2600 Brief to PM 08/5/13']