views:

219

answers:

3

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! :)

+6  A: 
l.sort(key = lambda x: x.timetuple()[1:3])
Laurence Gonsalves
BTW: I'm assuming that list is meant to be datetime objects (as mentioned in the first part of your question), and not strings (as shown in the code snippet).
Laurence Gonsalves
Yes, sorry about that. I changed the example to reflect what I meant to do. :)
Bryan Veloso
+6  A: 

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))
sth
+3  A: 

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
Adam Bernier