views:

223

answers:

4

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
A: 

read http://docs.python.org/library/datetime.html

Write your own function using date2 = date1 - timedelta(days=1) and date.isoweekday() iterating over previous days while isoweek is not equal to 3(Wednesday)

Roman A. Taycher
will certainly work, but this is awfully inefficient.
gurney alex
Awfully seems a bit harsh considering how few max comparisons, he asked for a function to get last wensday which probably won't get called that often(I do agree I threw something something together too fast.
Roman A. Taycher
A: 

I'm not sure if this meets your requirements, but it should get you the Wednesday closest to a given date the Wednesday in the same week as the given date, assuming weeks start on Monday:

import datetime

def find_closest_wednesday(date):
    WEDNESDAY = 3
    year, week, day  = date.isocalendar()
    delta = datetime.timedelta(days=WEDNESDAY-day)
    return date + delta

today = datetime.date.today()
print 'Today: ', today
print 'Closest Wendesday: ', find_closest_wednesday(today)
Will McCutchen
+5  A: 

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

today = date.today()
offset = (today.weekday() - 2) % 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() - 2) % 7
    last_wednesday = today - timedelta(days=offset)

    print last_wednesday
DisplacedAussie
A: 

Assuming that "last Wednesday" can't be the same as "today", this shows how to do it for any day of the week:

>>> from datetime import date
>>> from datetime import timedelta
>>>
>>> MON, TUE, WED, THU, FRI, SAT, SUN = range(7)
>>>
>>> def lastWday(adate, w):
...     """Mon:w=0, Sun:w=6"""
...     delta = (adate.weekday() + 6 - w) % 7 + 1
...     return adate - timedelta(days=delta)
...
>>> for x in range(8, 16):
...     start = date(year=2010, month=3, day=x)
...     prev = lastWday(start, WED)
...     print start, start.weekday(), prev, prev.weekday()
...
2010-03-08 0 2010-03-03 2
2010-03-09 1 2010-03-03 2
2010-03-10 2 2010-03-03 2
2010-03-11 3 2010-03-10 2
2010-03-12 4 2010-03-10 2
2010-03-13 5 2010-03-10 2
2010-03-14 6 2010-03-10 2
2010-03-15 0 2010-03-10 2
John Machin