python dynamic values to relativedelta function

884 views Asked by At

Im trying to provide dynamic value to relativedelta function, i.e relativedelta(days=1) i would like to assign dynamic function value days, months, years to the function. Consider my situation as follows. I will get list dynamicaly as follows:

Ex: 1

list = ['today', 'minus', '1', 'days']

Ex: 2

list = ['today', 'plus', '1', 'year']

Ex: 3

list = ['today', 'plus', '1', 'months']

I wrote my code to handle the calculation

import operator
from datetime import datetime
from datetime import date
from dateutil.relativedelta import relativedelta

operations = {
        'plus': operator.add,
        'minus': operator.sub,
    }
today = date.today()
new_date = self.operations['plus'](today, relativedelta(days=1))

# the above is some thing like [today + relativedelta(days=1)]

What I'm trying to do is like operations I would like to assign days, months, years to the relativedelta() function, but I couldn't able to do it. Any suggested way to do it?

1

There are 1 answers

0
DonOfDen On

Found a way to do it!

We can use the **expression call syntax to pass in a dictionary to a function instead, it'll be expanded into keyword arguments (which your **kwargs function parameter will capture again):

attributes = {'days': 1}
relativedelta(**attributes)