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 Dates and Times in Python (2014) Let's Build a Timed Quiz App Harder Time Machine

James Barber
James Barber
3,502 Points

How 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)

time_machine.py
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
akak
29,445 Points

I 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
James Barber
3,502 Points

Thanks 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.