Python 将指定的用户 days/months/years 添加到今天

Python add user specified days/months/years to today

我正在尝试将 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))

这允许用户指定日、月或年,并且 returns 使用 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