Using Python I would like to find the date object for last Wednesday. I can figure out where today is on the calendar using isocalendar, and determine whether or not we need to go back a week to get to the previous Wednesday. However, I can't figure out how to create a new date object with that information. Essentially, I need to figure out how to create a date from an iso calendar tuple.
from datetime import date
today = date.today()
if today.isocalendar()[2] > 3: #day of week starting with Monday
#get date for Wednesday of last week
else:
#get date for Wednesday of this current week
Practical Data Science using Python You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday). Finally add one week to this date using a timedelta object and voila you get the next monday's date.
weekly_thursday[-1] will give you the last Thursday of the month.
I think you want this. If the specified day is a Wednesday it will give you that day.
from datetime import date
from datetime import timedelta
from calendar import WEDNESDAY
today = date.today()
offset = (today.weekday() - WEDNESDAY) % 7
last_wednesday = today - timedelta(days=offset)
Example, the last wednesday for every day in March:
for x in xrange(1, 32):
today = date(year=2010, month=3, day=x)
offset = (today.weekday() - WEDNESDAY) % 7
last_wednesday = today - timedelta(days=offset)
print last_wednesday
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With