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
Khaleel Yusuf
15,208 PointsWrite a function named time_machine that takes an integer and a string of "minutes", "hours", "days", or "years". This d
I need so much help.
import datetime
starter = datetime.datetime(2015, 10, 21, 16, 29)
# Remember, you can't set "years" on a timedelta!
# Consider a year to be 365 days.
## Example
# time_machine(5, "minutes") => datetime(2015, 10, 21, 16, 34)
1 Answer
Chris Freeman
Treehouse Moderator 68,468 PointsHappy to help to walk you through the process!
The first step is to define the function signature. This is the line that declares the start of a function with the def keyword, followed by the desired name of the function. This function name is followed by parentheses with a list of expected parameters, if needed.
What would the function signature need to be for a function named time_machine that takes two arguments: an integer and a string?
(Leave your code as a comment below, and I'll ask you the next step by editing this post!)
Khaleel Yusuf
15,208 PointsKhaleel Yusuf
15,208 PointsChris Freeman
Treehouse Moderator 68,468 PointsChris Freeman
Treehouse Moderator 68,468 PointsGreat! So you have a received an argument on the amount of change in
integerand the units of the change instring. The next step is to define the amount of time changetimedelta()based on these two parameters. For example if the string is "minutes" you could use:change = datetime.timedelta(minutes=integer)But since you don't know in advance which unit type was passed in, how do you know which argument to pass to
timedelta? The simple approach is to use a series ofif ... elif ... elsestatements to compare the value ofstringto "minutes", "hours", "days", etc.In the case of "years", there isn't a
timedeltaparameter for 'years' so this section of code will have to convert theintegervalue to a usable value, such as "days", then use the "days" parameter intimedeltaCan you create the
if ... elif ... elsestatement to set a value to "change" based onintegerandstring?