import datetime
def date_week(date):
'''
功能:获取日期对应的周数(一年算52周,超过一年的范围,相同周数按照年区分)
week=00时周数算去年最后一周
判断 date 类型来分别做处理(字符串日期和日期类型)
:param date: 字符串日期,strptime方法 格式化规则
:return: 返回值,日期对应周数
'''
week = ''
if isinstance(date, str):
week = datetime.datetime.strptime(date, '%Y%m%d').strftime('%W')
if week == '00':
year = datetime.datetime.strptime(date, '%Y%m%d').year - 1
week = str(year) + '-52'
else:
week = datetime.datetime.strptime(date, '%Y%m%d').strftime('%Y-%W')
elif isinstance(date, datetime.datetime):
week = date.strftime('%W')
if week == '00':
year = date.year - 1
week = str(year) + '-52'
else:
week = date.strftime('%Y-%W')
else:
raise ValueError('{} 需要包含(年月日),字符串日期或者日期格式'.format(date))
return week