[Django]-How to get a list of dates from a week number in python

2👍

You can use Arrow for that:

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)

Output:

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]>]
👤1.618

4👍

Adapting this answer, you could do this with Python’s inbuilt modules – time, datetime.

Here’s the code:

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

Leave a comment