如何获取上周三的Python日期对象

时间:2010-03-04 18:36:55

标签: python datetime date

使用Python我想找到上周三的日期对象。我可以使用isocalendar找出今天在日历上的位置,并确定我们是否需要返回一周才能到达上周三。但是,我无法弄清楚如何使用该信息创建新的日期对象。基本上,我需要弄清楚如何从iso日历元组创建日期。

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

4 个答案:

答案 0 :(得分:40)

我想你想要这个。如果指定的日期是星期三,它会给你那一天。

from datetime import date
from datetime import timedelta

today = date.today()
offset = (today.weekday() - 2) % 7
last_wednesday = today - timedelta(days=offset)

例如,3月份每一天的最后一个星期三:

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

答案 1 :(得分:7)

假设“上周三”不能与“今天”相同,这表明如何在一周中的任何一天进行此操作:

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

答案 2 :(得分:-1)

阅读http://docs.python.org/library/datetime.html

使用date2 = date1 - timedelta(days = 1)和date.isoweekday()编写自己的函数,迭代前几天,而isoweek不等于3(星期三)

答案 3 :(得分:-1)

我不确定这是否符合您的要求,但它应该让您在给定日期的同一周内,在星期三最接近给定日期的情况下<星期三<假设>,假设周一开始几周:

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)