Jee
Jee

Reputation: 28

How pass dynamic arguments to the datetime.timedelta function?

I'm working on a python3 script where I use timedelta() function and need to pass parameters (keyword arguments with values) to timedelta() dynamically.

I tried several things but I can't figure out how to do this.

from datetime import timedelta

timeDeltaArgKey = "minutes"
timeDeltaArgValue = 60


timedelta(timeDeltaArgKey=timeDeltaArgValue)
# TypeError: 'timeDeltaArgKey' is an invalid keyword argument for __new__()

timedelta("{}={}".format(timeDeltaArgKey, timeDeltaArgValue))
# TypeError: unsupported type for timedelta days component: str

I also tried to pass it in as an array:

timeDeltaKwarg = {"minutes": 60}

timedelta(timeDeltaKwarg)
# TypeError: unsupported type for timedelta days component: dict

Upvotes: 1

Views: 1536

Answers (3)

martineau
martineau

Reputation: 123463

Create a keyword arguments dictionary and pass it to timedelta:

from datetime import timedelta


timeDeltaArg1Key = "days"
timeDeltaArg1Value = 3
timeDeltaArg2Key = "minutes"
timeDeltaArg2Value = 60

kwargs = {timeDeltaArg1Key: timeDeltaArg1Value, timeDeltaArg2Key: timeDeltaArg2Value}

result = timedelta(**kwargs)
print(result)  # -> 3 days, 1:00:00

Upvotes: 3

ugur
ugur

Reputation: 386

You need to use timedelta as follows:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Upvotes: 0

Fucio
Fucio

Reputation: 533

You need to unpack the dictionary to pass it:

timeDeltaKwarg = {"minutes": 60}
timedelta(**timeDeltaKwarg)

Or you can simply pass it as normal parameter

timedelta(minutes=60)

Upvotes: 1

Related Questions