Reputation: 486
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.
Upvotes: 3
Views: 752
Reputation: 521249
The following code defines a custom sorting function compare
which takes two elements from your list, and sorts them based on the date which appears at the start of each string. If you wanted to use the dates embedded at the end of the strings, you can modify the code accordingly.
def compare(item1, item2):
format = '%m/%d/%Y' #changed the date format
# convert string dates to Date type
date1 = datetime.datetime.strptime(item1[:10], format).date() #removed comma from item1[:,10]
date2 = datetime.datetime.strptime(item2[:10], format).date() #same as above
if date1 < date2:
return -1
elif date1 > date2:
return 1
else:
return 0
a = ["08/19/2014100%ABC10/02/2014F","02/12/2012100%ABC10/02/2014F",
"08/29/2014100%ABC10/02/2012F"]
a.sort(compare)
Upvotes: 0
Reputation: 87084
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')
Upvotes: 3