Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Python date object for last Wednesday

Tags:

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
like image 408
roktechie Avatar asked Mar 04 '10 18:03

roktechie


People also ask

How do I get the last Monday date in Python?

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.

How do I get the last Thursday of the month in Python?

weekly_thursday[-1] will give you the last Thursday of the month.


1 Answers

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
like image 73
DisplacedAussie Avatar answered Sep 17 '22 14:09

DisplacedAussie