Find yesterday today and tomorrow date in Python
In this tutorial, we will learn how to determine the date of yesterday, today, and tomorrow using Python. To retrieve the current date from the datetime module, we'll use datetime. today() function.
The following module will be imported:
- timedelta: This is a datetime module class that allows us to find the previous and next day's dates.
- datetime: Using the now() or today() methods, this module may assist us to find the current day.
Altering the date directly with increment and decrement will result in a fake Date, the timedelta class is utilized.
If the current date is the 31st of August, for example, incrementing the date immediately will result in the 32nd of August, which is incorrect. If we wish to directly alter the Date, we must first verify the day, month, and year, and then increment accordingly.
Let us now get familiar with the output console part:
Approach
The following is the approach of the program:
- The environment is set up with the necessary packages.
- The current date is determined using the now method in the DateTime package.
- It is then assigned to a variable.
- The timedelta method is used to find the previous or next days by passing a number as a parameter.
- To find the next day, the function is needed to be added.
- The day is subtracted if the previous day is to be found.
Algorithm
As of now, we have a rough understanding of how we will print desired dates. Let us now look at the algorithm followed by the code for better understanding:
- Import datetime and timedelta from datetime module
- Get today's date with help of today() function
- Get yesterday's date with help of today() function
- Get tomorrows' date with help of today() function
- Use strftime to print the desired dates.
Program
Let us now look at the program based on the above algorithm:
from datetime import datetime, timedelta
present = datetime.now()
yesterday = present - timedelta(1)
tomorrow = present + timedelta(1)
print("Yesterday was = ", yesterday.strftime('%d-%m-%Y'))
print("Today is= ", present.strftime('%d-%m-%Y'))
print("Tomorrow is = ", tomorrow.strftime('%d-%m-%Y'))
Yesterday was = 22-08-2021
Today is= 23-08-2021
Tomorrow is = 24-08-2021
Conclusion
In this tutorial, we have printed today's date, tomorrow's date, and present date using python. When it is required to find yesterday, today, and tomorrow’s date concerning the current date, the current time is determined, and a method is used that helps to find a previous day and next day’s dates.