#!/usr/bin/env python # -*- coding:utf-8 -*- import datetime import collections def date_list_fun(starttime,endtime): '''计算输入的起始日期和结束日期之间的所有日期''' _u=datetime.timedelta(days=1) startdate=datetime.datetime.strptime(starttime,'%Y%m%d') enddate=datetime.datetime.strptime(endtime,'%Y%m%d') n=0 date_list=[] if startdate<=enddate: # print startdate,enddate while 1: _time=startdate+n*_u date_list.append(_time.strftime('%Y%m%d')) n=n+1 if _time==enddate: break return date_list def allweeks(year): '''计算一年内所有周的具体日期,从1月1号开始,12.31号结束 输出如{1: ['20190101','20190106'],...} 只有六天 ''' start_date=datetime.datetime.strptime(str(year)+'0101','%Y%m%d') end_date=datetime.datetime.strptime(str(year)+'1231','%Y%m%d') _u=datetime.timedelta(days=1) n=0 week_date={} while 1: _time=start_date+n*_u w=str(int(_time.strftime('%W'))+1) week_date.setdefault(w,[]).append(_time.strftime('%Y%m%d')) n=n+1 if _time==end_date: break week_date_start_end={} for i in week_date: week_date_start_end[i]=[week_date[i][0],week_date[i][-1]] print week_date print week_date_start_end return week_date def all_weeks(year): '''计算一年内所有周的具体日期,每周都是7天,可能最后一周到 下年 week_date 输出如{1: ['20181231', '20190101', '20190102', '20190103', '20190104', '20190105', '20190106'],...} 计算一年内所有周的起始日期 week_date_start_end {1: ['20181231','20190106'],...} ''' start_date=datetime.datetime.strptime(str(int(year)-1)+'1224','%Y%m%d') end_date=datetime.datetime.strptime(str(int(year)+1)+'0107','%Y%m%d') _u=datetime.timedelta(days=1) n=0 week_date={} while 1: _time=start_date+n*_u y,w=_time.isocalendar()[:2] if y==year : week_date.setdefault(w,[]).append(_time.strftime('%Y%m%d')) n=n+1 if _time==end_date: break week_date_start_end={} for i in week_date: week_date_start_end[i]=[week_date[i][0],week_date[i][-1]] print week_date # print week_date_start_end return week_date,week_date_start_end
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/8057.html