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!
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
Asher OrrPython Development Techdegree Graduate 9,395 Points
My function is not returning the right datetime object- can anyone help me?
My function, time_machine, takes an integer and a string of "minutes", "hours", "days", or "years". The parameters describe a timedelta, and I want to return a datetime object that is the timedelta's duration from the starter datetime.
Here's my code:
# Remember, you can't set "years" on a timedelta! # Consider a year to be 365 days. import datetime starter = datetime.datetime(2015, 10, 21, 16, 29) def time_machine(int_obj, time_unit): if time_unit == "minutes": delta = datetime.timedelta(minutes=int_obj) if time_unit == "hours": delta = datetime.timedelta(hours=int_obj) if time_unit == "days": delta = datetime.timedelta(days=int_obj) if time_unit == "years": delta = datetime.timedelta(days=int_obj/365) new_obj = starter + delta return new_obj
I keep getting an error that time_machine doesn't return the right datetime. I would appreciate any insights on why this is occurring.
For what it's worth, I thought it might be an issue with converting the "if time_unit == 'years'" statement. I tried using floor division to see if I could get a more precise number that the checker would accept, like this:
if time_unit == "years": delta = datetime.timedelta(days=int_obj // 365)
But this hasn't worked either. Thank you for reading!
Mark SebeckTreehouse Moderator 36,463 Points
Hi Asher. The good news is you are super close. And the issues is not related to your understanding of Python. For years you have -
To set a year you want years * 365.