Home > Software design >  How to sort datetiems based on only month and day using list (not pandas)?
How to sort datetiems based on only month and day using list (not pandas)?

Time:12-14

I am working on python2 environment (codes for legacy softwares) and I do not have access to numpy and pandas. I stumbled with a problem:

How to sort datetiems using month and days only (not the year, it's for birthdates where only month and day matters).

My attempt

from datetime import date

lst = [date(2021,1,10), date(2020,3,1), date(2020,2,2), date(2020,2,1),date(2020,1,10)]

lst = sorted(lst)
print(lst)

[datetime.date(2020, 1, 10),
 datetime.date(2020, 2, 1),
 datetime.date(2020, 2, 2),
 datetime.date(2020, 3, 1),
 datetime.date(2021, 1, 10)]

Required

[datetime.date(2020, 1, 10),
 datetime.date(2021, 1, 10)
 datetime.date(2020, 2, 1),
 datetime.date(2020, 2, 2),
 datetime.date(2020, 3, 1),
 
]

CodePudding user response:

you have to define a sorting key

sorted(lst, key=lambda x: (x.month, x.day))

CodePudding user response:

Check out the [documentation][1] on the sort function. You can provide the key keyword argument that is used to extract a comparison key for each element of the list that is to be sorted. Since you want to sort only by month and day you can define the following key extraction function:

def key_month_day(dt):
    return 12*dt.month   dt.day

And then use it to sort your dates:

lst = sorted(lst, key=key_month_day)

[1]: https://docs.python.org/3/library/stdtypes.html#:~:text=following additional method:-,sort,-(*, key=None, reverse

  • Related