Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get the Python date object for last Wednesday?
You can get the Python date object for last Wednesday using date arithmetic. The key is calculating how many days back Wednesday was from today, regardless of what day it currently is.
Understanding the Logic
Python's weekday() method returns 0 for Monday, 1 for Tuesday, 2 for Wednesday, and so on. To find last Wednesday, we subtract 2 (Wednesday's index) from today's weekday and use modulo 7 to handle week boundaries ?
Example
from datetime import date, timedelta
today = date.today()
print(f"Today is: {today} ({today.strftime('%A')})")
# Calculate days back to last Wednesday
offset = (today.weekday() - 2) % 7
last_wednesday = today - timedelta(days=offset)
print(f"Last Wednesday was: {last_wednesday}")
Today is: 2024-01-15 (Monday) Last Wednesday was: 2024-01-10
How the Formula Works
The formula (today.weekday() - 2) % 7 works as follows ?
from datetime import date, timedelta
# Let's see how it works for different days
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for i, day in enumerate(days):
offset = (i - 2) % 7
print(f"{day}: go back {offset} days")
Monday: go back 6 days Tuesday: go back 0 days Wednesday: go back 1 days Thursday: go back 2 days Friday: go back 3 days Saturday: go back 4 days Sunday: go back 5 days
Complete Function
Here's a reusable function to get last Wednesday ?
from datetime import date, timedelta
def get_last_wednesday():
"""Returns the date object for the most recent Wednesday."""
today = date.today()
offset = (today.weekday() - 2) % 7
return today - timedelta(days=offset)
# Usage
last_wed = get_last_wednesday()
print(f"Last Wednesday: {last_wed.strftime('%Y-%m-%d (%A)')}")
Last Wednesday: 2024-01-10 (Wednesday)
Conclusion
Use (today.weekday() - 2) % 7 to calculate days back to last Wednesday. The modulo operation handles week boundaries, ensuring the formula works regardless of the current day.
Advertisements
