如何从python中的周数获取日期列表

时间:2015-04-24 18:38:29

标签: python django

所以我知道使用x = mydate.strftime("%U")的日期的周数我现在需要查找该周的所有日期。最后,我需要从日期对象上的django获取一个查询集,该查询集仅基于知道周数来返回给定周内的所有记录。类似的东西:

y = Stuff.objects.filter=(date__range=[#anydate that is in the week number of x])

2 个答案:

答案 0 :(得分:2)

适应this answer,您可以使用Python的内置模块 - 时间,日期时间。

以下是代码:

import time
import datetime

WEEK  = 21
startdate = time.asctime(time.strptime('2008 %d 1' % WEEK, '%Y %W %w'))
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y')
dates = [startdate]
for i in range(1, 7):
    dates.append(startdate + datetime.timedelta(days=i))

print dates

## -- End pasted text --
[datetime.datetime(2008, 5, 26, 0, 0), datetime.datetime(2008, 5, 27, 0, 0), datetime.datetime(2008, 5, 28, 0, 0), datetime.datetime(2008, 5, 29, 0, 0), datetime.datetime(2008, 5, 30, 0, 0), datetime.datetime(2008, 5, 31, 0, 0), datetime.datetime(2008, 6, 1, 0, 0)]

答案 1 :(得分:1)

您可以使用箭头:

import arrow

def get_week(dt):
    mydate = arrow.get(dt)
    start = mydate.floor('week')
    end = mydate.ceil('week')
    return arrow.Arrow.range('day', start, end)

输出:

In [369]: list(get_week(datetime.datetime.utcnow()))
Out[369]: 
[<Arrow [2015-04-20T00:00:00+00:00]>,
 <Arrow [2015-04-21T00:00:00+00:00]>,
 <Arrow [2015-04-22T00:00:00+00:00]>,
 <Arrow [2015-04-23T00:00:00+00:00]>,
 <Arrow [2015-04-24T00:00:00+00:00]>,
 <Arrow [2015-04-25T00:00:00+00:00]>,
 <Arrow [2015-04-26T00:00:00+00:00]>]