Pass expression in argument name name

I am using dateutil.relativedelta()

that named arguments that match time_unit

in my age

-tuple and the code to get the relative time looks like this:

def time_delta(age):
    now = datetime.fromtimestamp(int(time.time()))
    if age.time_unit == "seconds":
        relative_time = now - relativedelta(seconds=int(age.value))
    elif age.time_unit == "minutes":
        relative_time = now - relativedelta(minutes=int(age.value))
    elif age.time_unit == "hours":
        relative_time = now - relativedelta(hours=int(age.value))
    elif age.time_unit == "days":
        relative_time = now - relativedelta(days=int(age.value))
    elif age.time_unit == "weeks":
        relative_time = now - relativedelta(weeks=int(age.value))
    elif age.time_unit == "months":
        relative_time = now - relativedelta(months=int(age.value))
    elif age.time_unit == "years":
        relative_time = now - relativedelta(years=int(age.value))

      

Is there any way in Python 2.7 to do this in one layer using something line by line:

relative_time = now - relativedelta(eval("eval('age.time_unit') +'=' +age.value"))

      

The above doesn't work. Am I stuck with if/elif

or is there something nicer I could do here?

+3


source to share


2 answers


def time_delta(age):
    now = datetime.fromtimestamp(int(time.time()))
    return now - relativedelta(**{age.time_unit: int(age.value)})

      



(the code hasn't been tested but should probably work)

+5


source


def time_delta(age):
    now = datetime.fromtimestamp(int(time.time()))
    if age.time_unit in ["seconds","minutes","hours","days","weeks","months","years"]:
        exec("relative_time = now - relativedelta({}=int(age.value))".format(age.time_unit))

      

I know, I know. exec

!!! It's safe in this mode guys.



Edit: Typo. exec

, but noteval

0


source







All Articles