w3resource

Python: Get the date of the last Tuesday


19. Last Tuesday Finder

Write a Python program to get the date of the last Tuesday.

Sample Solution:

Python Code:

# Import the date class from the datetime module
from datetime import date
# Import the timedelta class from the datetime module
from datetime import timedelta

# Get the current date and assign it to the variable 'today'
today = date.today()

# Calculate the offset needed to go back to the most recent Tuesday
# This is done by finding the difference between the current weekday and Tuesday (1), and taking modulo 7
offset = (today.weekday() - 1) % 7

# Calculate the date of the most recent Tuesday by subtracting the offset from the current date
last_tuesday = today - timedelta(days=offset)

# Print the date of the most recent Tuesday
print(last_tuesday) 

Output:

2017-05-02 

Explanation:

In the exercise above,

  • The code imports the "date" class and the "timedelta" class from the "datetime" module.
  • Get current date:
    • It retrieves the current date using the "date.today()" method and assigns it to the variable 'today'.
  • Calculating Offset for most recent Tuesday:
    • It calculates the offset needed to go back to the most recent Tuesday from the current date.
    • This is done by finding the difference between the current weekday (today.weekday()) and Tuesday (1, where Monday is 0), then taking modulo 7 to ensure the offset loops back to Tuesday if the current day is Tuesday.
  • Find the most recent Tuesday:
    • It calculates the date of the most recent Tuesday by subtracting the calculated offset from the current date using "timedelta(days=offset)".
  • Finally it prints the date of the most recent Tuesday.

Flowchart:

Flowchart: Get the date of the last Tuesday.

For more Practice: Solve these Related Problems:

  • Write a Python program to find the date of the last Tuesday before today and then display it in "Month Day, Year" format.
  • Write a Python script to calculate the previous Tuesday from any given date using date arithmetic.
  • Write a Python function that returns the date of the last Tuesday and also prints how many days ago it was from today.
  • Write a Python program to determine the last Tuesday in the previous month and compare it with the last Tuesday of the current month.

Go to:


Previous: Write a Python program to get days between two dates.
Next: Write a Python program to test the third Tuesday of a month.

Python Code Editor:

Contribute your code and comments through Disqus.

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.