Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Dates and Times in Python 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.