返回使用python跨越另一年的ISO周列表

时间:2017-08-17 02:44:12

标签: python pandas strptime

我正在尝试转换一个yyyyww,它实际上是作为一个字符串对象开始,我认为就像201731。我想捕捉过去6周,包括它的自我。

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)

所以201731的输出应该是:

 [201731, 201730, 201729, 201728, 201727, 201726]

这似乎有效,问题是如果我用201702这样的交叉年测试它会返回:

   [201702, 201701, 201700, 201651, 201650, 201649]

这也看起来不错,但我需要在ISO周内这样,所以我认为不应该有一周00,一年的最后一周应该是53或52而不是51。

任何想法如何适应这个?

2 个答案:

答案 0 :(得分:0)

我对striptime()一无所知。所以我通过编写自己的代码解决了这个问题。这是代码:

date=input()

a=int(date[0:4])
b=int(date[4:])

k=5-b

finallist=[]

def m(x,y):
    return(x-y)


if b>=5:
    date=int(date)
    finallist=[date,date-1,date-2,date-3,date-4,date-5]
    print(finallist)

else:
    date=int(date)
    for i in range(b+1):
        finallist.append(date)
        date-=1
    a-=1
    b=52
    date=int(str(a)+str(b))
    for i in range(k):
        finallist.append(date)
        date-=1
    print(finallist)
  

201700提供[201700, 201652, 201651, 201650, 201649, 201648]

     

201702提供[201702, 201701, 201700, 201652, 201651, 201650]

ALITER :有一种更简单的方法可以做到这一点。只需在列表中的特定列表项中添加1:p

答案 1 :(得分:0)

这需要安装“isoweek”软件包,但是通过对我的str YYYYWW格式的一些操作给了我想要的东西,并且适合交叉年。

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