我正在尝试在今天的日期中添加 x 天、月数或年数,其中 x 和频率都由用户提供。
我已经看过dateutil.relativedelta
但由于它不接受字符串作为参数,我本可以尝试myStr=‘months=+6’
然后使用relativedelta(myStr)
我不知道该怎么办。任何提示将不胜感激。
谢谢。
您可以在此处使用relativedelta
,只需正确指定即可。
确保将今天的日期也指定为datetime
对象。
from datetime import datetime
from dateutil.relativedelta import relativedelta
def add_calander(dmy, date):
if dmy == 'D':
value = int(input('How many days would you like to add?'))
date = date + relativedelta(days=value)
if dmy == 'M':
value = int(input('How many months would you like to add?'))
date = date + relativedelta(months=value)
if dmy == 'Y':
value = int(input('How many years would you like to add?'))
date = date + relativedelta(years=value)
return date
today = datetime.now()
dmy = input('Do you want to add days (D), months (M) or years (Y) to todays date?')
print(add_calander(dmy, today))
这允许用户指定日、月或年,并使用relativedelta
返回基于calendar
年的计算值。
结果:
Do you want to add days (D), months (M) or years (Y) to todays date?M
How many months would you like to add?5
2020-10-15 08:19:56.814910
Do you want to add days (D), months (M) or years (Y) to todays date?Y
How many years would you like to add?10
2030-05-15 08:20:03.624634
Do you want to add days (D), months (M) or years (Y) to todays date?D
How many days would you like to add?6
2020-05-21 08:20:24.311311