python计算两个时间段之内的年月和周。整理一下!

def get_datelist(self, starttime, endtime):
'''获取时间段内年月份'''
startdate = datetime.datetime.strptime(str(starttime),'%Y-%m-%d')
endtime = datetime.datetime.strptime(str(endtime),'%Y-%m-%d')

delta = startdate.month

n = 0
date_list = []
while 1:
if startdate <= endtime:
year_month = self.add_months(startdate, n)
n = n + 1
date_list.append(str(year_month.year)+str(year_month.month))
if year_month.year == endtime.year and year_month.month == endtime.month:
break
return date_list

def add_months(self, dt, months):
''' 月份相加 '''
targetmonth = months + dt.month
try:
dt = dt.replace(year=dt.year+int(targetmonth/12),month=(targetmonth%12))
except:
dt = dt.replace(year=dt.year+int((targetmonth+1)/12), month=((targetmonth+1)%12), day=1)
dt += datetime.timedelta(days=-1)
return dt

 

def startdate_enddate_weeks_list(self, startdate, enddate):
'''计算startdate---enddate的周所属的周列表
week_date_start_end {1: ['20181231','20190106'],...}
'''
import collections
start_date=datetime.datetime.strptime(str(startdate),'%Y-%m-%d')
end_date=datetime.datetime.strptime(str(enddate),'%Y-%m-%d')
_u=datetime.timedelta(days=1)
n=0

week_date = {}
date = []
while 1:
_time = start_date+n*_u
y, w = _time.isocalendar()[:2]
year_week = str(y) + str(w)
if week_date.has_key(year_week):
date.append(_time.strftime('%Y-%m-%d'))
else:
date = [_time.strftime('%Y-%m-%d')]
week_date[year_week] = date
n=n+1
if _time == end_date:
break

return week_date.keys()

posted @ 2016-10-31 20:00  菜鸟到大神的蜕变  阅读(782)  评论(0编辑  收藏  举报