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

Using variable inside of a timedelta/function

So I know you can do this to print a variable in a string.

foo = hey
print('{} Is a var'.format(foo))

but how would i insert a variable into here?

foo = 'hours'
bar = 2
print(datetime.timedelta('{}={}'.format(foo,bar))

1 Answer

timedelta doesn't accept a String as its parameter; it accepts a key (i.e. hours, minutes, days, etc.) and a value (i.e. some integer) with the assignment operator (=) between them.

You can only insert a variable as the value in timedelta's parameter:

bar = 2
print(datetime.timedelta(hours=bar))

If you want to provide multiple options with different time units for the key, you need to either make multiple timedeltas, or you need to convert the values that correspond to those keys to values that correspond to a single key (e.g. converting hours to minutes and days to minutes so you're only working with the minutes key).

I hope this helps!

Thank you! This does help!

You're welcome!