Add Days to a Date in Python

Add Days to a Date in Python

Syed Moiz Haider Dec-10, 2020 Nov-30, 2020 Python Python DateTime
  1. Use datetime.timedelta() to Add Days to a Date in Python
  2. Use timedelta in datetime Module to Add Days to the Current Date
  3. Use Pandas Module to Add Days to a Date in Python

The tutorial explains how to add days to a date in Python.

Use datetime.timedelta() to Add Days to a Date in Python

In Python, datetime module provides a datetime.timedelta() method. It takes the number of days to be added as its argument and returns the date. The datetime.strptime() method of datetime() module takes the start date as its input and returns the same date in the format of datetime.datetime.

An example code is given as:

import datetime

curr_date = "12/6/20"
curr_date_temp = datetime.datetime.strptime(curr_date, "%m/%d/%y")

new_date = curr_date_temp + datetime.timedelta(days=5)
print(new_date)

Output:

2020-12-11 00:00:00

Use timedelta in datetime Module to Add Days to the Current Date

The Python datetime has the timedelta method itself besides the timedelta from its submodule datetime. The timedelta() method takes the number of days to be added as its argument and returns them in date format. The date module also has a today() method, which returns the current date.

A basic example of this approach is given as:

from datetime import timedelta, date

Date_required = date.today() + timedelta(days=5)
print(Date_required)

Output:

2020-12-05

Use Pandas Module to Add Days to a Date in Python

Pandas module provides a to_datetime() method that takes a date as its argument and converts it into a pandas._libs.tslibs.timestamps.Timestamp object. Pandas will do the smart converting if the format of the date string is not specified.

The DateOffset() method takes the keyword arguments like days, months and etc. It returns a pandas.tseries.offsets.DateOffset object.

An example code is given below:

import pandas as pd

initial_date = "12/5/2019"
req_date = pd.to_datetime(initial_date) + pd.DateOffset(days=3)
print(req_date)

Output:

2019-12-08 00:00:00

Related Article - Python DateTime

  • Convert Pandas Column to Datetime
  • Get the Current Time in Python
  • Get the Day of the Week in Python
  • Convert String to Datetime in Python
  • Find the Last Day of the Month Using Python
  • Determine Leap Year in Python