;

How to Add or Subtract a Day from a Given Date to Get a Specific Date in Python


Tutorialsrack 01/04/2020 Python

In this article, we will learn how to add or subtract a day from a given date to get a specific date in python.

Example 1: In this example, we will use datetime.timedelta() method from datetime module to add or subtract a day from a given date to get a specific date.

Example 1
# Import Module
import datetime

# Given Date
given_Date=datetime.datetime(2020,3,31)
print("\nGiven Date: ",given_Date.strftime("%d-%m-%Y"))
# Output ==> Given Date:  31-03-2020

# Add days to achieve Specific Date
specific_Date = datetime.datetime.today() + datetime.timedelta(days=10)

print("\nSpecific Date: ",specific_Date.strftime("%d-%m-%Y"))
# Output ==> Specific Date:  11-04-2020

Example 2: In this example, we just create a method to add or subtract a day from a given date to get a specific date.

Example 2
# Import Module
import datetime

def AddDaysToDate(date,days):    
    specific_Date = date + datetime.timedelta(days=days)
    return specific_Date.strftime("%d-%m-%Y")

print("\nNext Day Date: ",AddDaysToDate(datetime.datetime(2020,3,31),1))
# Output ==> Next Day Date:  01-04-2020

print("\nPrevious Day Date: ",AddDaysToDate(datetime.datetime(2020,3,31),1))
# Output ==> Previous Day Date:  01-04-2020

print("\n31 Days before Date: ",AddDaysToDate(datetime.datetime(2020,3,31),-31))
# Output ==> 31 Days before Date:  29-02-2020

I hope this article will help you to understand how to add or subtract a day from a given date to get a specific date in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags