开发者

How to get the Python date object for last Wednesday

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 开发者_JAVA技巧week starting with Monday
    #get date for Wednesday of last week
else:
    #get date for Wednesday of this current week


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


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


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)


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜