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 trialBrad Pettigrew
1,834 PointsArgument format for timedelta
Hey I'm running into a bit of trouble with one of the python track challenges. I'm trying to take a string (time) and an int variable (length of time) and return a timedelta equivalent to the two. E.g. time = days, int = 5, return timedelta(days=5). However, I have trouble simply plugging the variables into the timedelta function. If I do not convert my integer to a string, python says it cannot implicitly convert int to str, but if I convert to string, python says the timedelta function does not take str input. So how should I input my string and integer into the timedelta function?
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)
def time_machine(int, time):
if time == "years":
int *= 365
time = "days"
return starter + datetime.timedelta(time + "=" + int)
1 Answer
Hanley Chan
27,771 PointsHi
This should work. I put your time and integer into a dictionary.
return starter + datetime.timedelta(**{time: int})
Bryan Manhollan
Courses Plus Student 10,096 PointsBryan Manhollan
Courses Plus Student 10,096 PointsGlad this was here because I would have never thought of doing it this way. :)
Could anyone tell me why time=num portion doesn't work in the return? I kept getting a "time is an invalid keyword argument for this function". Not sure why the string will manually set in this manner but won't set if used as a variable.