I have a list of links that all contain dates in the form yyyymmdd. I am attempting to sort those links. I started a function that is passed a list of links that I have previously converted to strings. I would like this function to return a list with those links sorted. This is how I've started but I am unsure how to proceed.
def sort_bydate(links):
for l in links:
#get date part of string
s = l[48:56]
#convert to datetime
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))
CodePudding user response:
sorted(links, key=lambda l: l[48:56])
. Sorting a string with the format yyyymmdd
doesn't require converting it to a datetime.
CodePudding user response:
You can shorten your function to just return the tuple of ints, and pass that to the key
argument of sorted
.
def get_date_tuple(link):
s = link[48:56]
return (int(s[0:4]), int(s[4:6]), int(s[6:8]))
sorted(links, key=get_date_tuple)
However, because numeric strings are naturally sortable, you really don't need to convert to ints, you can just use the substring of the date.