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 trialJames Barber
3,502 PointsHow to properly combine str and int variables to construct a valid argument for timedelta()
How do I combine str and int variables to construct a valid argument for timedelta() in the following line of code? timedelta = datetime.timedelta(time_units + "=" + time_int)
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(time_int, time_units):
if time_units == "years":
time_int *= 365
time_units = "days"
timedelta = datetime.timedelta(time_units + "=" + int(time_int))
return starter + timedelta
1 Answer
akak
29,445 PointsI wrote almost exact same code as you today. After some time I gave up and looked up forum for the answer. The only one I found was indicating that you need to make timedelta for every case (hours, minutes etc.). You can't provide variable time_units instead of word. So if, elif, elif and so on.
def time_machine(integer, string1):
if string1 == 'hours':
return starter + datetime.timedelta(hours=integer)
elif string1 == 'days':
return starter + datetime.timedelta(days=integer)
James Barber
3,502 PointsJames Barber
3,502 PointsThanks akak, that was the work-around I came up with too (just so I could pass the quiz...). It felt overly-difficult though, so I'd be very curious if anyone knows a cleaner way to implement this code.