Im试图为relativelta函数提供动态值,即relativedelta(days=1)
我想将动态函数值days
、months
、years
分配给该函数。考虑我的情况如下。我将得到列表动态如下:
Ex: 1
list = ['today', 'minus', '1', 'days']
Ex: 2
list = ['today', 'plus', '1', 'year']
Ex: 3
list = ['today', 'plus', '1', 'months']
我写代码来处理的计算
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)]
我想做的是像operations
一样。我想把days
、months
、years
分配给relativedelta()
函数,但我做不到。有什么建议的方法吗?
找到了一种方法!
我们可以使用**expression
调用语法将字典传递给函数,相反,它将被扩展为关键字参数(**kwargs
函数参数将再次捕获(:
attributes = {'days': 1}
relativedelta(**attributes)