I am trying to convert a yyyyww which is actually starting as a string object I think at is like 201731. I want to capture the last 6 weeks including its self.
def generate_6_last_week(yearweek):
weeks = [int(yearweek)]
date = time.mktime(datetime.strptime(str(yearweek)+"0","%Y%W%w").timetuple())
for i in range(1,6):
date = date-604800 # 60*60*24*7
weeks.append(int(datetime.fromtimestamp(int(date)).strftime('%Y%W')))
return weeks
generate_6_last_week(201731)
so the output for 201731 should be:
[201731, 201730, 201729, 201728, 201727, 201726]
and this seems to work, the problem is if i test it with a crossover year like 201702 it returns this:
[201702, 201701, 201700, 201651, 201650, 201649]
Which also looks pretty good, but I need it in ISO weeks so there shouldnt be a week 00 I think and the last week of a year should be either 53 or 52 but not the 51.
Any ideas how to adapt this?
This requires the "isoweek" package to be installed but gave me what i want with some manipulation of the format of my str YYYYWW and works well with the crossover years.
from isoweek import Week
yearweek = "201702"
weeks = [int(yearweek)]
x = 1
for i in range(5):
week = int(str(Week(int(yearweek[:4]), int(yearweek[-2:])-x)).replace("W",""))
weeks.append(week)
x +=1
print(weeks)
def generate_6_last_week(yearweek):
weeks = [int(yearweek)]
x = 1
for i in range(5):
week = int(str(Week(int(yearweek[:4]), int(yearweek[-2:])-x)).replace("W",""))
weeks.append(week)
x +=1
print(weeks)
generate_6_last_week("201702")