0
4

1 回答 1

1

You can use relativedelta here, you just need to specify it correctly.

Make sure you specify today's date as a datetime object as well.

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))

This allows a user to specify the day, month or year and returns a calculated value based off the calendar year using relativedelta.

Results:

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
于 2020-05-14T22:21:51.140 回答