Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the week numbers between two dates with python

I'd like to find the most pythonic way to output a list of the week numbers between two dates.

For example:

input

start = datetime.date(2011, 12, 25) 
end = datetime.date(2012, 1, 21)

output

find_weeks(start, end)
>> [201152, 201201, 201202, 201203]

I've been struggling using the datetime library with little success

like image 576
Ludo Avatar asked Dec 19 '22 01:12

Ludo


1 Answers

Something in the lines of (update: removed less-readable option)

import datetime

def find_weeks(start,end):
    l = []
    for i in range((end-start).days + 1):
        d = (start+datetime.timedelta(days=i)).isocalendar()[:2] # e.g. (2011, 52)
        yearweek = '{}{:02}'.format(*d) # e.g. "201152"
        l.append(yearweek)
    return sorted(set(l))

start = datetime.date(2011, 12, 25) 
end = datetime.date(2012, 1, 21)

print(find_weeks(start,end)[1:]) # [1:] to exclude first week.

Returns

['201152', '201201', '201202', '201203']

To include the first week (201151) simply remove [1:] after function call

like image 160
Anton vBR Avatar answered Dec 27 '22 02:12

Anton vBR