简体   繁体   中英

Sort by Date Python List

I've got a list with both the date in human readable form and the date format, I'm trying to make it sort the dates.

it fails to return the correct order.

d = ["10-8-2015@Mon, Aug 10, 2015", "11-8-2015@Tue, Aug 11, 2015", "12-8-2015@Wed, Aug 12, 2015","13-8-2015@Thu, Aug 13, 2015", "14-8-2015@Fri, Aug 14, 2015", "7-8-2015@Fri, Aug 07, 2015", "8-8-2015@Sat, Aug 08, 2015", "9-8-2015@Sun, Aug 09, 2015"]
>>> def sorting(L):
...     splitup = L.split('-')
...     return splitup[1], splitup[0]
... 
>>> sorted(d, key=sorting)
['10-8-2015@Mon, Aug 10, 2015', '11-8-2015@Tue, Aug 11, 2015', '12-8-2015@Wed, Aug 12, 2015', '13-8-2015@Thu, Aug 13, 2015', '14-8-2015@Fri, Aug 14, 2015', '7-8-2015@Fri, Aug 07, 2015', '8-8-2015@Sat, Aug 08, 2015', '9-8-2015@Sun, Aug 09, 2015']

You can use time.strptime

>>> from time import strptime
>>> sorted(d, key = lambda i: strptime(i.split('@')[0], '%d-%m-%Y'))
['7-8-2015@Fri, Aug 07, 2015',
 '8-8-2015@Sat, Aug 08, 2015',
 '9-8-2015@Sun, Aug 09, 2015',
 '10-8-2015@Mon, Aug 10, 2015',
 '11-8-2015@Tue, Aug 11, 2015',
 '12-8-2015@Wed, Aug 12, 2015',
 '13-8-2015@Thu, Aug 13, 2015',
 '14-8-2015@Fri, Aug 14, 2015']

Basically, you can split at the '@' character, then all of your strings can be used to create struct_time objects. You can use a lambda in the key argument of sorted to sort by these struct_time objects.

Also note that you can reverse the sort order using the reverse argument

>>> sorted(d, key = lambda i: strptime(i.split('@')[0], '%d-%m-%Y'), reverse=True)
['14-8-2015@Fri, Aug 14, 2015',
 '13-8-2015@Thu, Aug 13, 2015',
 '12-8-2015@Wed, Aug 12, 2015',
 '11-8-2015@Tue, Aug 11, 2015',
 '10-8-2015@Mon, Aug 10, 2015',
 '9-8-2015@Sun, Aug 09, 2015',
 '8-8-2015@Sat, Aug 08, 2015',
 '7-8-2015@Fri, Aug 07, 2015']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM