Home > Net >  sorting by month, week number (integer with string) and year in Python
sorting by month, week number (integer with string) and year in Python

Time:12-13

In python, i have an array of dates in this format (January, Week 1, 2022). I would like to sort first by year, then month and then week number.

Just to give a visual representation, below is one example of an array of dates.

January, Week 4, 2022 
January, Week 3, 2022
January, Week 2, 2022
December, Week 5, 2022
November, Week 1, 2021
October, Week 5, 2021
October, Week 2, 2021
September, Week 3, 2021
September, Week 1, 2021
August, Week 1, 2021

CodePudding user response:

There are multiple solutions, but if you don't mind to use hack for it, you can use strptime with proper format:

from datetime import datetime

s = "January, Week 4, 2022"
fmt = "%B, Week %d, %Y"
dtime = datetime.strptime(s, fmt)

Here %B stands for month full name, %Y is a year and (here is a hack) %d is a day. If we prepare list of datetimes we can sort it with their natural order

sorted([datetime.strptime(s, fmt) for s in input_list]) # or with reverse=True

At the end you can return to str format with datetime.strftime

CodePudding user response:

This should get you started.. If you use the sort() function. It arranges based on your requirements (ascending, depending etc..)

from datetime import datetime
my_dates = ['5-Nov-18', '25-Mar-17', '1-Nov-18', '7-Mar-17']
my_dates.sort(key=lambda date: datetime.strptime(date, "%d-%b-%y"))
print(my_dates)
  • Related