TypeError: start_end_period() got an unexpected keyword argument 'months'
我正在为这个错误而苦苦挣扎。由于可以执行
relativedelta.relativedelta(test)
,其中某些内容可能直接是months=1
的years=1
,所以我想将test
作为参数直接传递给start_end_period()
方法。start_date = CustomerProfile.objects.filter(user__date_joined__gte=entry_date_production).first().user.date_joined
def start_end_period(period):
start = start_date - relativedelta.relativedelta(period)
end = start + relativedelta.relativedelta(period - 1)
return start, end
由于
relativedelta(7)
和relativedelta(months=1)
都很好,我如何才能适应这种方法,使其与单个参数或关键字参数一起使用? 最佳答案
首先,您不能将数月或数年传递给需要一定时间但不花费数日,数月或数年的功能。将功能声明为您想要的功能。
然后,您将需要将它们传递给relativedelta构造函数。这是最简单的方法
from dateutil.relativedelta import relativedelta
def start_end_period(start_date, days=0, months=0, years=0):
period = relativedelta(days=days, months=months, years=years)
start = start_date - period
end = start + period + relativedelta(days=1)
return start, end
import datetime
start_date = datetime.date(year=2017, month=3, day=1)
print (start_date)
print (start_end_period(start_date, days=7))
print (start_end_period(start_date, months=2))
print (start_end_period(start_date, years=1))
但是,您应该改用** kwargs,它会通过传递给函数的任何值自动支持所有relativedelta的选项。
def start_end_period(start_date, **kwargs):
period = relativedelta(**kwargs)
关于python - TypeError:start_end_period()获得了意外的关键字参数“months”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46414221/