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

Welby Obeng
Welby Obeng
20,340 Points

why TypeError: 'duration' is an invalid keyword argument for this function

why do I get TypeError: 'duration' is an invalid keyword argument for this function for this code

import datetime

starter = datetime.datetime(2015, 10, 21, 16, 29)

def time_machine (int, duration):
  if duration == "years":
    int = int * 365
    duration = "days"
  return datetime.timedelta(duration=int)



print(time_machine(5,"minutes"))

2 Answers

Hi Welby,

You're getting that error because 'duration' isn't a valid keyword argument for timedelta

duration is a argument that is passed into your time_machine function which holds a string of whatever the time unit was. The valid choices for keyword arguments are : 'days, seconds, microseconds, milliseconds, minutes, hours or weeks'

So when you try to pass in duration as a keyword argument it's interpreting that literally as an argument named duration which isn't in that list.

What you could do is create a dictionary out of the 2 passed in arguments and then unpack that dictionary when passing it into datetime.timedelta

# suppose duration was "days" and int was 5
datetime.timedelta(**{duration:int}) # becomes datetime.timedelta(days=5)

The other problem that you're having is that you're returning the timedelta rather than a new datetime that is the starter time plus the timedelta.

Also, I would recommend not using int for your argument since it's reserved as a data type in python and may cause you problems depending on what you're doing with your code.

Ivan Bodnar
Ivan Bodnar
2,419 Points

Thanks, I had the exact same problem and I couldn't find the answer. I suspected it had to do with unpacking but I didn't know how.

the colour formatting should give you the clue.. int is a special keyword and you shouldnt use it as a variable..

Also i think the problem might be this: return datetime.timedelta(duration=integer) .. you need to pass in the args a different way as far as I remember.. you should create a dict and then pass that in.