Python Program to Find and Display the Next Previous Date of a Given Date

Python program to generate and display the next date of a given date; Through this tutorial, i am going to show you how to validate a given date and find the next date in python.

In this tutorial, i will implement a program to find and display the next and previous date of a given date in python program.

Python Program to Find and Display the Next Previous Date of a Given Date

  • 1: Python program to find the date on next day if today’s date is given by user
  • 2: Python program to find the date on the previous day if today’s date is given by user

1: Python program to find the date on next day if today’s date is given by user

  • Import datetime module and as well as timedelta object of datetime module in program.
  • Get input day, month, and year from user.
  • Format the user-inputted date using the datetime.datetime() function.
  • Add the one day of the given formatted date.
  • Print result.
import datetime
from datetime import timedelta 
d=int(input("ENTER THE DAY : "))
m=int(input("ENTER THE MONTH : "))
y=int(input("ENTER THE YEAR : "))
    
# format given date
gDate = datetime.datetime(y, m, d) 
print("Given date is: ", gDate) 
  
# Yesterday date 
yesterday = gDate + timedelta(days = 1) 
print("Next date will be : ", yesterday) 

After executing the program, the output will be

ENTER THE DAY :  26
ENTER THE MONTH :  04
ENTER THE YEAR :  2020
Given date is:  2020-04-26 00:00:00
Next date will be :  2020-04-27 00:00:00

Explanation of above python program:- In the above given python program, i have used datetime.datetime() module to format the given date . And also use givenDate + datetime. timedelta(days=1) to add one day from the given date and print result as next date in python.

2: Python program to find the date on the previous day if today’s date is given by user

  • Import datetime module and as well as timedelta object of datetime module in program.
  • Get input day, month, and year from user.
  • Format the user-inputted date using the datetime.datetime() function.
  • Subtract the one day from the given formatted date.
  • Print result.
import datetime
from datetime import timedelta 
d=int(input("ENTER THE DAY : "))
m=int(input("ENTER THE MONTH : "))
y=int(input("ENTER THE YEAR : "))
    
# format given date
gDate = datetime.datetime(y, m, d) 
print("Given date is: ", gDate) 
  
# previous date 
pv = gDate - timedelta(days = 1) 
print("Previous date was : ", pv) 

After executing the program, the output will be

ENTER THE DAY :  26
ENTER THE MONTH :  04
ENTER THE YEAR :  2020
Given date is:  2020-04-26 00:00:00
Previous date was :  2020-04-25 00:00:00

In this above given python program, I have used datetime.datetime() to format the given date. And also use givenDate – datetime. timedelta(days=1) to substract one day from the given date and print result as previous date in python.

Recommended Python Tutorials

Leave a Comment