Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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),
 
]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you have to define a sorting key

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading