Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting a list containing dates as a substring

Tags:

python

I have a list of strings something like this As you can make out there is a date embedded at the start of the string and also at the end of the string.

 a = ["08/19/2014100%ABC10/02/2014F","02/12/2012100%ABC10/02/2014F",
      "08/29/2014100%ABC10/02/2012F"]

I wanted to sort this list based on the date substring.

The way I wanted to implement is by extract the date, sort the date and join the date with the substring, but it's becoming too complicated.

like image 744
Android Beginner Avatar asked Aug 11 '26 17:08

Android Beginner


1 Answers

Just call sorted() with the key argument set to a function that extracts and converts the date from the string into a datetime.datetime object.

>>> from datetime import datetime
>>> a = ["08/19/2014100%ABC10/02/2014F","02/12/2012100%ABC10/02/2014F", "08/29/2014100%ABC10/02/2012F"]
>>> sorted_a = sorted(a, key=lambda s: datetime.strptime(s[:10], '%m/%d/%Y'))
>>> sorted_a
['02/12/2012100%ABC10/02/2014F', '08/19/2014100%ABC10/02/2014F', '08/29/2014100%ABC10/02/2012F']

Or, if you want to sort in place:

>>> a.sort(key=lambda s: datetime.strptime(s[:10], '%m/%d/%Y'))
>>> a
['02/12/2012100%ABC10/02/2014F', '08/19/2014100%ABC10/02/2014F', '08/29/2014100%ABC10/02/2012F']

If you actually mean to sort on the last date in the string just change the key function to:

lambda s: datetime.strptime(s[-11:-1], '%m/%d/%Y')
like image 163
mhawke Avatar answered Aug 13 '26 06:08

mhawke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!