Javaexercise.com

How to Add Days in Python Date?

This article is all about adding days to date. It contains several examples to explain how to add days in python date. In python, we can do this by using the following ways:

  • datetime and timedelta
  • date.today and timedelta
  • datetime and pandas
  • datetime and now

We will use all these functions and modules to create a new date after adding days. We can any number of days such as 1, 2, 10, etc. 

Example to Add days to Python date using datetime and timedelta

Here, we used the strptime() method to parse the date into a specified format and create a date object. After that, we use timedelta() method to add days to this date object. See the below example

import datetime
# Take a date
startDate = "10/5/20"
# Parse date 
date = datetime.datetime.strptime(startDate, "%m/%d/%y")
# Print date
print("A Date:",date)
# Add days to date
new_date = date + datetime.timedelta(days=2)
# Print new date
print("New Date:",new_date)

 

Example to Add Days in Current Date or Today's Date in Python

Python Date can be any date or the current date. Here, we used today() method to create a date object, and then by using timedelta() method we added days to it.

import datetime
from datetime import timedelta, date

# Take a date
startDate = date.today()
# Print date
print("A Date:",startDate)
# Add days to date
new_date = startDate + datetime.timedelta(days=2)

# Print new date
print("New Date:",new_date)

 

Example: Add days to Python date using Pandas

If you are working with pandas then you can use the DateOffset() method of pandas to add days to the python date. See the below example.

import pandas as pd
from datetime import timedelta, date

# Take a date
startDate = "2020-10-20"
# Print date
print("A Date:",startDate)
# Add days to date
new_date = pd.to_datetime(startDate) + pd.DateOffset(days=2)

# Print new date
print("New Date:",new_date)

 

Example: Add Days to Current date in Python using now() Method

The now() method returns the current timestamp in python. We used timedelta() to add days and strftime() method to format the date into the specified format.

from datetime import datetime
from datetime import timedelta

# Take a date
startDate = datetime.now()
# Print date
print("A Date:",startDate)
# Add days to date
new_date = (startDate + timedelta(days=2)).strftime('%Y-%m-%d')

# Print new date
print("New Date:",new_date)

 

Related Articles