w3resource

Python: Print yesterday, today, tomorrow


7. Relative Dates Printer

Write a Python program to print yesterday, today, tomorrow.

Sample Solution:

Python Code:

# Import the datetime module
import datetime 

# Get the current date using datetime.date.today()
today = datetime.date.today()

# Calculate yesterday's date by subtracting 1 day from today's date using timedelta(days=1)
yesterday = today - datetime.timedelta(days=1)

# Calculate tomorrow's date by adding 1 day to today's date using timedelta(days=1)
tomorrow = today + datetime.timedelta(days=1) 

# Print yesterday's date
print('Yesterday : ', yesterday)

# Print today's date
print('Today : ', today)

# Print tomorrow's date
print('Tomorrow : ', tomorrow)

Output:

Yesterday :  2017-05-05                                                                                       
Today :  2017-05-06                                                                                           
Tomorrow :  2017-05-07  

Explanation:

In the exercise above,

  • The code imports the "datetime" module, which provides functionalities to work with dates and times.
  • Get Current Date:
    • It retrieves the current date using the "datetime.date.today()" method and assigns it to the variable 'today'.
  • Calculating Previous and Next Dates:
    • It calculates yesterday's date by subtracting one day from the current date ('today') using the "datetime.timedelta(days=1)" function. The result is assigned to the variable 'yesterday'.
    • It calculates tomorrow's date by adding one day to the current date ('today') using the "datetime.timedelta(days=1)" function. The result is assigned to the variable 'tomorrow'.
  • Finally it prints the calculated dates ('yesterday', 'today', and 'tomorrow') along with their corresponding labels.

Flowchart:

Flowchart: Print yesterday, today, tomorrow.

For more Practice: Solve these Related Problems:

  • Write a Python program to print yesterday’s, today’s, and tomorrow’s dates in "YYYY-MM-DD" format using date arithmetic.
  • Write a Python script that displays the dates for the day before yesterday, yesterday, today, tomorrow, and the day after tomorrow.
  • Write a Python program to compute and print yesterday, today, and tomorrow along with the corresponding weekday names.
  • Write a Python function to output relative dates (yesterday, today, tomorrow) and check if today is the first day of the month.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to convert unix timestamp string to readable date.
Next: Write a Python program to convert the date to datetime (midnight of the date).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.