Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Functional Python Functional Workhorses attrgetter

Andy Hughes
Andy Hughes
8,479 Points

Question - where does attribute 'day' come from?

Just a question to help my confusion. In this code challenge I used the following code line, which passed the challenge.

sorted_dates = sorted(date_list, key=attrgetter('day'))

But originally I used this, which failed:

sorted_dates = sorted(date_list, key=attrgetter('%d'))

My question is; where does 'day' come from as an attribute? It's not explicitly mentioned in the code anywhere. So, more by experimenting, I put the word 'day' in.

Second question :P; So how would I ordinarily know that the attribute is called 'day'. Is it from the docs? Did I miss it in an older video? (ok maybe it wasn't just one question lol).

It's confused me though and I don't like staying confused! :)

sorting.py
import datetime
from operator import attrgetter

date_list = [
    datetime.datetime(2015, 4, 29, 10, 15, 39),
    datetime.datetime(2006, 8, 15, 14, 59, 2),
    datetime.datetime(1981, 5, 16, 2, 10, 42),
    datetime.datetime(2012, 8, 9, 14, 59, 2),
]

sorted_dates = sorted(date_list, key=attrgetter('day'))

1 Answer

Steven Parker
Steven Parker
231,275 Points

This was likely covered in a previous video, but if you refer to the documentation for the datetime object, you can see that any object of this type has an attribute named "day" that represents the day number of the month.

Andy Hughes
Andy Hughes
8,479 Points

Thanks for your answer. I suspect it might have been mentioned in a video, way back. It's hard to keep this stuff in your memory when you're not using it daily. I'm still trying to get used to reading the docs and trying to understand quite what they are saying. :P. Thanks again.

Steven Parker
Steven Parker
231,275 Points

Actually, one of the things I enjoy about answering forum questions is that it helps me to remember all this stuff myself. :wink:

Happy holidays! :christmas_tree: