Syntax error Find yesterday’s, today’s and tomorrow’s date in Python

Find yesterday’s, today’s and tomorrow’s date in Python



When it is required to find yesterday, today and tomorrow’s date with respect to current date, the current time is determined, and a method is used (in built) that helps find previous day and next day’s dates.

Below is a demonstration of the same −

Example

 Live Demo

from datetime import datetime, timedelta

present = datetime.now()
yesterday = present - timedelta(1)
tomorrow = present + timedelta(1)

print("Yesterday was :")
print(yesterday.strftime('%d-%m-%Y'))
print("Today is :")
print(present.strftime('%d-%m-%Y'))
print("Tomorrow would be :")
print(tomorrow.strftime('%d-%m-%Y'))

Output

Yesterday was :
05-04-2021
Today is :
06-04-2021
Tomorrow would be :
07-04-2021

Explanation

  • The required packages are imported into the environment.

  • The current date is determined using the ‘now’ method present in ‘datetime’ package.

  • It is assigned to a variable.

  • The ‘timedelta’ method is used to find the previous or next days, by passing the number as parameter.

  • When the next day has to be found, the function is added.

  • When the previous day has to be found, the function is subtracted.

  • The output is displayed on the console.

Updated on: 2021-04-15T13:05:43+05:30

466 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements