用python / django倒计时4周(每周一周)

时间:2013-12-07 17:57:17

标签: python django

有人可以知道我如何在给定年份的4周后倒计时,然后计算每周的start_date和end_date吗?

这就是我现在所拥有的:

def FourWeeks(year, week):
    d = date(year, 1, 1)
    delta_days = d.isoweekday() - 1
    fourweekback = [week - x for x in range(4)]
    for delta_weeks in fourweekback:
        delta = timedelta(days=-delta_days, weeks=delta_weeks)
        weekbeg = datetime.datetime.combine(d, datetime.time(00, 00, 01)) + delta
        delta2 = timedelta(days=6-delta_days, weeks=delta_weeks)
        weekend = datetime.datetime.combine(d, datetime.time(23, 59, 59)) + delta2
    return (fourweekback, weekbeg, weekend)

输出:

FourWeeks(2013, 44)
    ([40, 39, 38, 37], datetime.datetime(2013, 10, 7, 0, 0, 1), datetime.datetime(2013, 10, 13, 23, 59, 59))
    ([40, 39, 38, 37], datetime.datetime(2013, 9, 30, 0, 0, 1), datetime.datetime(2013, 10, 6, 23, 59, 59))
    ([40, 39, 38, 37], datetime.datetime(2013, 9, 23, 0, 0, 1), datetime.datetime(2013, 9, 29, 23, 59, 59))
    ([40, 39, 38, 37], datetime.datetime(2013, 9, 16, 0, 0, 1), datetime.datetime(2013, 9, 22, 23, 59, 59))
    ([40, 39, 38, 37], datetime.datetime(2013, 9, 16, 0, 0, 1), datetime.datetime(2013, 9, 22, 23, 59, 59))

这就是我想要实现的目标:

FourWeeks(2013, 44)
    (44, datetime.datetime(2013, 10, 28, 0, 0, 1), datetime.datetime(2013, 11, 3, 23, 59, 59))
    (39, datetime.datetime(2013, 9, 23, 0, 0, 1), datetime.datetime(2013, 9, 29, 23, 59, 59))
    (38, datetime.datetime(2013, 9, 16, 0, 0, 1), datetime.datetime(2013, 9, 22, 23, 59, 59))
    (37, datetime.datetime(2013, 9, 9, 0, 0, 1), datetime.datetime(2013, 9, 15, 23, 59, 59))

在下一步中,我喜欢使用weekbeg,周末

进行查询
cursor.execute("SELECT * FROM event WHERE datetime BETWEEN %s AND %s, [weekbeg, weekend] )

知道我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

您应该能够调整以下内容(注意它使用可通过pip& co轻松安装的第三方dateutil):

from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, WEEKLY, MO, SU
from datetime import datetime, timedelta

def four_weeks(year, week):
    end = datetime(year, 1, 1) + relativedelta(weeks=week-1, weekday=SU)
    start = end - relativedelta(weeks=4, weekday=MO)
    mint, maxt = datetime.min.time(), datetime.max.time()
    for dt in rrule(WEEKLY, start, count=4):
        yield dt.combine(dt, mint), dt.combine(dt + timedelta(days=6), maxt)

for start, end in four_weeks(2013, 44):
    print start, '->', end

输出:

2013-10-07 00:00:00 -> 2013-10-13 23:59:59.999999
2013-10-14 00:00:00 -> 2013-10-20 23:59:59.999999
2013-10-21 00:00:00 -> 2013-10-27 23:59:59.999999
2013-10-28 00:00:00 -> 2013-11-03 23:59:59.999999