Search code examples
pythondatetimepython-dateutilrelativedelta

Python add user specified days/months/years to today


I am trying to add x number of days or months or years to today’s date, where both x and the frequency are supplied by the user.

I have looked at dateutil.relativedelta but since it doesn’t accept a string as a parameter, where I could have perhaps tried myStr=‘months=+6’ and then used relativedelta(myStr) I’m not sure what to do. Any tips would be appreciated.

Thanks.


Solution

  • 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