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

neoty888
neoty888
23,973 Points

attrgetter

I don't know how to pass to sorted the day in the datetime tuple.

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(datetime.datetime[1])

4 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Ty;

Many apologies for the confusion, too many things running through my brain tonight.

Since our data is converted into datetime data, we can use attrgetter to "get" information a bit easier. In this case since we are looking for the Day attribute we can do attrgetter('day').

Again, sorry for the initial confusion. I hope this gets you going in the right direction. I'll delete my other answers so that they don't cause confusion down the road.

Happy coding,
Ken

neoty888
neoty888
23,973 Points

sorted_dates = sorted(date_list, key=attrgetter(2))

I just tried that, still no go.

Ty

neoty888
neoty888
23,973 Points

I understood that part, I figured the '1' position was the month rather than the day.

Regardless, I tried this:

sorted_dates = sorted(date_list, key=attrgetter(1))

and I received the following:

'attribute name must be a string'

neoty888
neoty888
23,973 Points

I think it's late for the both of us. It didn't dawn upon me till you just mentioned it!! :)

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

The above works. I can't believe I was overthinking this.

Ken Alger
Ken Alger
Treehouse Teacher

It stumped me for a bit initially as well, and I guess that initial thought lingered around my head too long.

Thanks for hanging in there.