如果我很理解您的问题,我认为您可以使用datetime和{}从{}模块中解决它,如下例:from datetime import datetime, timedelta
def get_days_of_week(year, week=1):
# number of the days
days = {'Monday': 1, 'Tuesday': 2, 'Wednesday': 3,
'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7}
# construct the datetime object with the year and the desired week
a = datetime.strptime('{0}'.format(year), '%Y') + timedelta(days=7*(week-1))
# Every week should start by Sunday .. So escaping days untill the first Sunday
a += timedelta(days=7-days.get(a.strftime('%A'), 0))
for k in range(0, 7):
yield (a + timedelta(days=k)).strftime('%Y%m%d')
days = list(get_days_of_week(2016, week=1))
print('2016 / week = 1:', days)
days = list(get_days_of_week(2016, week=22))
print('2016 / week = 22:', days)
输出:
^{pr2}$
编辑:
根据您上次的编辑,此代码可以满足您的需要:from datetime import datetime, timedelta
def get_days_of_week(data):
# number of the days
days = {'Monday': 1, 'Tuesday': 2, 'Wednesday': 3,
'Thursday': 4, 'Friday': 5, 'Saturday': 6, 'Sunday': 7}
date = datetime.strptime('{}'.format(data), '%Y%m%d')
# get week number
week = int(date.strftime('%U'))
# get year
year = date.strftime('%Y')
# construct the datetime object with the year and the desired week
a = datetime.strptime(year, '%Y') + timedelta(days=7*week)
# Every week should start by Synday .. So escaping days untill the first Sunday
a += timedelta(days=7-days.get(a.strftime('%A'), 0))
return {int(str(data)[:-2]): [int((a + timedelta(days=k)).strftime('%Y%m%d')) for k in range(0, 7)]}
week_dict = {}
week_dict.update(get_days_of_week(20160101))
week_dict.update(get_days_of_week(20160623))
print(week_dict[201601])
print(week_dict[201606])
print(week_dict)
输出:[20160103, 20160104, 20160105, 20160106, 20160107, 20160108, 20160109]
[20160626, 20160627, 20160628, 20160629, 20160630, 20160701, 20160702]
{ 201601: [ 20160103,
20160104,
20160105,
20160106,
20160107,
20160108,
20160109],
201606: [ 20160626,
20160627,
20160628,
20160629,
20160630,
20160701,
20160702]}