如何根据python中的周数获取周的所有日期

lea*_*ent 5 python datetime python-2.7

我想要基于周数的当前周的所有日期。

我可以得到周数

import datetime
weeknum=datetime.datetime.now().isocalendar()[1]
Run Code Online (Sandbox Code Playgroud)

结果是 20。

想要第 20 周的所有日期。最终输出应该是

dates=['2019-05-12','2019-05-13','2019-05-14','2019-05-15','2019-05-16','2019-05-17','2019-05-18']
Run Code Online (Sandbox Code Playgroud)

请帮我。

Ser*_*ach 7

你可以做到这一点time,并datetime这个答案建议,但它改变你的要求:

WEEK  = 20 - 2 # as it starts with 0 and you want week to start from sunday
startdate = time.asctime(time.strptime('2019 %d 0' % WEEK, '%Y %W %w')) 
startdate = datetime.datetime.strptime(startdate, '%a %b %d %H:%M:%S %Y') 
dates = [startdate.strftime('%Y-%m-%d')] 
for i in range(1, 7): 
    day = startdate + datetime.timedelta(days=i)
    dates.append(day.strftime('%Y-%m-%d')) 
Run Code Online (Sandbox Code Playgroud)

输出如下:

dates = ['2019-05-12',
         '2019-05-13',
         '2019-05-14',
         '2019-05-15',
         '2019-05-16',
         '2019-05-17',
         '2019-05-18']
Run Code Online (Sandbox Code Playgroud)


Wil*_*ill 6

使用 timedelta 和列表理解。

import datetime
theday = datetime.date.today()
weekday = theday.isoweekday()
# The start of the week
start = theday - datetime.timedelta(days=weekday)
# build a simple range
dates = [start + datetime.timedelta(days=d) for d in range(7)]
Run Code Online (Sandbox Code Playgroud)

获取字符串输出

dates = [str(d) for d in dates]
Run Code Online (Sandbox Code Playgroud)