Sort list of urls by datetime path component

Viewed 208

I have a list of urls that have a multiple datetime components.

urls = [ www.google.com/2018-10-26/2018-10-26T11:07:10.000Z, www.google.com//2018-10-26/2018-10-26T11:09:18.000Z]

I want to sort on it and then return the list back like this:

urls = [ www.google.com/2018-10-26/2018-10-26T11:09:18.000Z, www.google.com//2018-10-26/2018-10-26T11:07:10.000Z]

Because the first element has 2018-10-26T11:09:18.000Z it is greater than 2018-10-26T11:07:10.000Z. Is there a way to do this in a list comprehension? I am assuming this is the right path:

for url in urls:
   date = url.split('/')[2]

But not sure what to do from there.

2 Answers

You can sort your urls inplace based on the timestamp (i.e. the last element after the slash) in reverse order (most recent first) via:

urls.sort(key=lambda url: url.split('/')[-1], reverse=True)

You can sort the list using a function to define the sort key. For example:

urls = ['www.google.com/2018-10-26/2018-10-26T11:07:10.000Z', 'www.google.com//2018-10-26/2018-10-26T11:09:18.000Z']

sorted_urls = sorted(urls, key=lambda x: x.split('/')[-1], reverse=True)
print(sorted_urls)
# OUTPUT
# ['www.google.com//2018-10-26/2018-10-26T11:09:18.000Z', 'www.google.com/2018-10-26/2018-10-26T11:07:10.000Z']
Related