gpt4 book ai didi

python - 类型错误 : start_end_period() got an unexpected keyword argument 'months'

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:44 25 4
gpt4 key购买 nike

TypeError: start_end_period() got an unexpected keyword argument 'months'

我正在努力解决这个错误。由于可以执行relativedelta.relativedelta(test),其中某些内容可以直接是years=1months=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 - 类型错误 : start_end_period() got an unexpected keyword argument 'months' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com