Issue
I have a list of dates extracted from a website which I want to sort in ascending order. The list being obtained is as follows:
['\u200e02-09-2021', '\u200e08-03-2022', '\u200e08-03-2022', '\u200e08-03-2022', '\u200e06-09-2021', '\u200e03-23-2021', '\u200e03-23-2021', '\u200e02-10-2021', '\u200e02-10-2021']
The dates are in mm-dd-yyyy format but they are not sorted in ascending order. I tried using the .sort() method but it ended up giving a None list. Can anyone please help me sort this out in ascending order?
The code I am using is as follows:
for i in range(0, len(links)):
url = links[i]
response = requests.get(url, cookies)
soup = BeautifulSoup(response.content)
un = [q.text for q in soup.find_all(class_='lia-link-navigation lia-page-link lia-user-name-link')]
date = [j.text for j in soup.find_all(class_='local-date')]
time = [k.text for k in soup.find_all(class_='local-time')]
j = len(time)
for q in (0, j):
print(date)
Solution
We can try sorting using a lambda function which sorts based on the date rearranged into an ISO format:
dates = ['\u200e02-09-2021', '\u200e08-03-2022', '\u200e08-03-2022', '\u200e08-03-2022', '\u200e06-09-2021', '\u200e03-23-2021', '\u200e03-23-2021', '\u200e02-10-2021', '\u200e02-10-2021']
dates.sort(key=lambda x: x[-4:] + x[-10:-8] + x[-7:-5])
print(dates)
This prints:
['\\u200e02-09-2021', '\\u200e02-10-2021', '\\u200e02-10-2021',
'\\u200e03-23-2021', '\\u200e03-23-2021', '\\u200e06-09-2021',
'\\u200e08-03-2022', '\\u200e08-03-2022', '\\u200e08-03-2022']
Answered By - Tim Biegeleisen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.