Python - Adding days, months or years to a string date

  • Adding days, months or years to a python date is straight forward, if we are doing this on datetime objects.

    But sometimes, the dates that we are going to use may be in string format. Here we will have to first convert string dates to datetime and then do the addition.

    Converting string to datetime can be challenging because the dates can be in different formats. Below samples uses a string date in mm-dd-yy format.

    For more samples on string to date conversion refer Convert String to Datetime - All Formats

  • Add Days

    Copied
    import datetime
    
    stringdate = "02-25-22"
    
    formatteddate = datetime.datetime.strptime(stringdate, '%m-%d-%y')
    formatteddate = formatteddate + datetime.timedelta(days = 10)
    
    print(formatteddate)
    
    Output:
      2022-03-07 00:00:00
  • Add Months

    Adding month to a date is not as easy as adding days. timedelta doesn't support adding months. We will have to create a new date object as shown below.

    Copied
    import datetime
    
    stringdate = "02-25-22"
    
    formatteddate = datetime.datetime.strptime(stringdate, '%m-%d-%y')
    monthstoadd = 5
    newdate = datetime.datetime(formatteddate.year, formatteddate.month + monthstoadd, formatteddate.day)
    
    print(newdate)
    
    Output:
      2022-07-25 00:00:00
  • Add Years

    Do this in the same way as adding months.

    Copied
    import datetime
    
    stringdate = "02-25-22"
    
    formatteddate = datetime.datetime.strptime(stringdate, '%m-%d-%y')
    yearstoadd = 5
    newdate = datetime.datetime(formatteddate.year + yearstoadd, formatteddate.month, formatteddate.day)
    
    print(newdate)
    
    Output:
      2027-02-25 00:00:00
  • Add Days, Months or Years using dateutil

    Another easier way of doing this is using python dateutil library.
    We will have to install dateutil using the command pip install python-dateutil and add days, months or years as below.

    Copied
    import datetime
    from dateutil.relativedelta import relativedelta
    
    stringdate = "02-25-22"
    
    formatteddate = datetime.datetime.strptime(stringdate, '%m-%d-%y')
    yearstoadd = 7
    newdate = formatteddate + relativedelta(years=+yearstoadd)
    
    print(newdate)
    
    Output:
      2029-02-25 00:00:00
Absolute Code Works - Python Topics