主要包括:
获取指定日期对应哪一年的第几周、获取当前日期对应哪一年的第几周、获取当前日期这一周的第一天的日期、获取指定周的第一天日期。
/Users/nisj/PycharmProjects/EsDataProc/bi-static/getWeekInfo.py
/Users/nisj/PycharmProjects/EsDataProc/bi-static/getWeekInfo.py
# -*- coding=utf-8 -*-
import datetime
def getYearWeek(strdate):
date = datetime.datetime.strptime(strdate, '%Y-%m-%d')
YearWeek = date.isocalendar()
return YearWeek
def getNowYearWeek():
# 当前时间年第几周的计算
timenow = datetime.datetime.now()
NowYearWeek = timenow.isocalendar()
return NowYearWeek
def getDayInweekMonday():
week_num = datetime.datetime.now().weekday()
Monday = datetime.datetime.now() + datetime.timedelta(days=-week_num)
Monday = str(Monday)[0:10]
return Monday
# weekflag格式为"2016#53"(即2016年第53周)
def getWeekFirstday(weekflag):
year_str = weekflag[0:4] # 取到年份
week_str = weekflag[5:] # 取到周
if int(week_str)>=53:
Monday = "Error,Week Num greater than 53!"
else:
yearstart_str = year_str + '0101' # 当年第一天
yearstart = datetime.datetime.strptime(yearstart_str, '%Y%m%d') # 格式化为日期格式
yearstartcalendarmsg = yearstart.isocalendar() # 当年第一天的周信息
yearstartweekday = yearstartcalendarmsg[2]
yearstartyear = yearstartcalendarmsg[0]
if yearstartyear < int(year_str):
daydelat = (8 - int(yearstartweekday)) + (int(week_str) - 1) * 7
else:
daydelat = (8 - int(yearstartweekday)) + (int(week_str) - 2) * 7
Monday = (yearstart + datetime.timedelta(days=daydelat)).date()
return Monday
if __name__ == '__main__':
strdate = '2017-01-01'
print getYearWeek(strdate)
print getNowYearWeek()
print getDayInweekMonday()
# 输出2014年第35周的开始时间
print getWeekFirstday('2019#1')
测试结果:
/usr/bin/python /Users/nisj/PycharmProjects/EsDataProc/bi-static/getWeekInfo.py
(2016, 52, 7)
(2017, 1, 5)
2017-01-02
2018-12-31
Process finished with exit code 0