Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting datetime objects while ignoring the year?

I have a list of birthdays stored in datetime objects. How would one go about sorting these in Python using only the month and day arguments?

For example,

[
    datetime.datetime(1983, 1, 1, 0, 0)
    datetime.datetime(1996, 1, 13, 0 ,0)
    datetime.datetime(1976, 2, 6, 0, 0)
    ...
]

Thanks! :)

like image 305
Bryan Veloso Avatar asked Jan 11 '10 05:01

Bryan Veloso


3 Answers

You can use month and day to create a value that can be used for sorting:

birthdays.sort(key = lambda d: (d.month, d.day))
like image 119
sth Avatar answered Nov 09 '22 04:11

sth


l.sort(key = lambda x: x.timetuple()[1:3])
like image 41
Laurence Gonsalves Avatar answered Nov 09 '22 03:11

Laurence Gonsalves


If the dates are stored as strings—you say they aren't, although it looks like they are—you might use dateutil's parser:

>>> from dateutil.parser import parse
>>> from pprint import pprint
>>> bd = ['February 6, 1976','January 13, 1996','January 1, 1983']
>>> bd = [parse(i) for i in bd]
>>> pprint(bd)
[datetime.datetime(1976, 2, 6, 0, 0), 
 datetime.datetime(1996, 1, 13, 0, 0), 
 datetime.datetime(1983, 1, 1, 0, 0)]
>>> bd.sort(key = lambda d: (d.month, d.day)) # from sth's answer
>>> pprint(bd)
[datetime.datetime(1983, 1, 1, 0, 0),
 datetime.datetime(1996, 1, 13, 0, 0),
 datetime.datetime(1976, 2, 6, 0, 0)]

If your dates are in different formats, you might give fuzzy parsing a shot:

>>> bd = [parse(i,fuzzy=True) for i in bd] # replace line 4 above with this line
like image 20
mechanical_meat Avatar answered Nov 09 '22 02:11

mechanical_meat