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)
CodePudding user response:
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']
CodePudding user response:
Just extending @Emre's comment
from datetime import datetime
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']
sortedDates = sorted([datetime.strptime(date.strip('\u200e'), '%m-%d-%Y') for date in dates])
print(sortedDates)
prints
[datetime.datetime(2021, 2, 9, 0, 0), datetime.datetime(2021, 2, 10, 0, 0), datetime.datetime(2021, 2, 10, 0, 0), datetime.datetime(2021, 3, 23, 0, 0), datetime.datetime(2021, 3, 23, 0, 0), datetime.datetime(2021, 6, 9, 0, 0), datetime.datetime(2022, 8, 3, 0, 0), datetime.datetime(2022, 8, 3, 0, 0), datetime.datetime(2022, 8, 3, 0, 0)]