Python 从字典创建 dateutil.relativedelta.relativedelta object 的方法
Python method to create a dateutil.relativedelta.relativedelta object from a dict
我正在使用以下方法创建标题中所述的 object:
from dateutil import relativedelta
MA_dict = {'years': 0,
'months': 0,
'weeks': 0,
'days': 1,
'hours': 0,
'minutes': 0,
'seconds': 0}
def dict2relativedelta(dict):
'''
creates relativedelta variable that can be used to calculate dates
'''
dt = relativedelta.relativedelta(years=dict['years'], months=dict['months'], weeks=dict['weeks'], days=dict['days'],
hours=dict['hours'], minutes=dict['minutes'], seconds=dict['seconds'])
return dt
但是,我想简化这个,这样我就可以通过
MA_dict = {'days': 1}
与函数return相同。我该怎么做?
您不需要为此使用特殊函数,因为 Python 具有使用 **
运算符解包的参数。您可以通过以下方式完成您想要的:
MA_dict = {"days": 1}
rd = relativedelta.relativedelta(**MA_dict)
我正在使用以下方法创建标题中所述的 object:
from dateutil import relativedelta
MA_dict = {'years': 0,
'months': 0,
'weeks': 0,
'days': 1,
'hours': 0,
'minutes': 0,
'seconds': 0}
def dict2relativedelta(dict):
'''
creates relativedelta variable that can be used to calculate dates
'''
dt = relativedelta.relativedelta(years=dict['years'], months=dict['months'], weeks=dict['weeks'], days=dict['days'],
hours=dict['hours'], minutes=dict['minutes'], seconds=dict['seconds'])
return dt
但是,我想简化这个,这样我就可以通过
MA_dict = {'days': 1}
与函数return相同。我该怎么做?
您不需要为此使用特殊函数,因为 Python 具有使用 **
运算符解包的参数。您可以通过以下方式完成您想要的:
MA_dict = {"days": 1}
rd = relativedelta.relativedelta(**MA_dict)