str as param for timedelta

P

Philipp

Hello Pythonistas

I'm new to Python, I hope you understand my question.
I would like to pass a parameter "gap" to a function. gap should be
used there to create a timedelta Object.

from datetime import *

def f(gap):
print (datetime.now() + datetime.timedelta(gap))

f('hours = -8')

I read in the manual that datetime does accept ints, longs, or floats,
which may be positive or negative. Same as the error message:
"unsupported type for timedelta days component: str"

I found out, that I can pass an Object

def f1(deltaObj):
print (datetime.now() + deltaObj)

f1(timedelta(hours = -8))

I would prefer the first version, as it is easier to use the string for
representation and so on.

Is there any way to pass a string to the function and use it there for
the timedelta?

or you might say I missed some basic concepts...

.... in any case, thank you very much!

Phil
 
D

dylan.moreland

Philipp said:
from datetime import *

def f(gap):
print (datetime.now() + datetime.timedelta(gap))

f('hours = -8')

When you need a flexible input format, consider keyword arguments. In
this case, I would pass along the inputs to timedelta:

def from_now(**kwargs):
return datetime.now() + timedelta(**kwargs)

from_now(hours=8) returns datetime.now() + timedelta(hours=8), and the
function can now accept any of timedelta's arguments. For more on what
**kwargs means, see the tutorial:

http://docs.python.org/tut/node6.html#SECTION006720000000000000000
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top