Skip to main content

How to add days to a given date in Python

How to add days to a given date in Python.

Here's a detailed step-by-step tutorial on how to add days to a given date in Python. We will cover different methods to achieve this:

Method 1: Using the datetime module

  1. Import the datetime module by adding the following line at the top of your Python script:
import datetime
  1. Create a datetime object representing the given date. You can do this by calling the datetime.datetime class and passing the year, month, and day as arguments. For example, to represent the date January 1, 2022, you would use:
given_date = datetime.datetime(2022, 1, 1)
  1. Define the number of days you want to add to the given date. For example, if you want to add 7 days, you would use:
num_days = 7
  1. Use the timedelta function from the datetime module to add the specified number of days to the given date. The timedelta function takes the number of days as an argument and returns a timedelta object. You can add this timedelta object to the given date using the + operator. For example, to add 7 days to the given date, you would use:
new_date = given_date + datetime.timedelta(days=num_days)
  1. The variable new_date now holds the updated date after adding the specified number of days to the given date. You can print it to verify the result:
print(new_date)

Here's the complete code:

import datetime

given_date = datetime.datetime(2022, 1, 1)
num_days = 7
new_date = given_date + datetime.timedelta(days=num_days)
print(new_date)

Method 2: Using the dateutil module

  1. Install the dateutil module if you haven't already. You can do this by running the following command in your terminal:
pip install python-dateutil
  1. Import the dateutil module by adding the following line at the top of your Python script:
from dateutil.relativedelta import relativedelta
  1. Create a datetime object representing the given date. You can do this using the datetime.datetime class, similar to Method 1.

  2. Define the number of days you want to add to the given date, similar to Method 1.

  3. Use the relativedelta function from the dateutil module to add the specified number of days to the given date. The relativedelta function takes the number of days as an argument and returns a relativedelta object. You can add this relativedelta object to the given date using the + operator, similar to Method 1.

  4. The variable new_date now holds the updated date after adding the specified number of days to the given date. You can print it to verify the result, similar to Method 1.

Here's the complete code:

from dateutil.relativedelta import relativedelta

given_date = datetime.datetime(2022, 1, 1)
num_days = 7
new_date = given_date + relativedelta(days=num_days)
print(new_date)

That's it! You now know how to add days to a given date in Python using two different methods. Choose the one that suits your needs best.