python获取指定日期范围内的每一天,每个月,每季度的方法
1.获取所有天,返回一个列表:
defgetBetweenDay(begin_date):
date_list=[]
begin_date=datetime.datetime.strptime(begin_date,"%Y-%m-%d")
end_date=datetime.datetime.strptime(time.strftime('%Y-%m-%d',time.localtime(time.time())),"%Y-%m-%d")
whilebegin_date<=end_date:
date_str=begin_date.strftime("%Y-%m-%d")
date_list.append(date_str)
begin_date+=datetime.timedelta(days=1)
returndate_list
2.获取所有月,返回一个列表:
defgetBetweenMonth(begin_date):
date_list=[]
begin_date=datetime.datetime.strptime(begin_date,"%Y-%m-%d")
end_date=datetime.datetime.strptime(time.strftime('%Y-%m-%d',time.localtime(time.time())),"%Y-%m-%d")
whilebegin_date<=end_date:
date_str=begin_date.strftime("%Y%m")
date_list.append(date_str)
begin_date=add_months(begin_date,1)
returndate_list
defadd_months(dt,months):
month=dt.month-1+months
year=dt.year+month/12
month=month%12+1
day=min(dt.day,calendar.monthrange(year,month)[1])
returndt.replace(year=year,month=month,day=day)
3.获取所有季度,返回一个列表:
defgetBetweenMonth(begin_date):
date_list=[]
begin_date=datetime.datetime.strptime(begin_date,"%Y-%m-%d")
end_date=datetime.datetime.strptime(time.strftime('%Y-%m-%d',time.localtime(time.time())),"%Y-%m-%d")
whilebegin_date<=end_date:
date_str=begin_date.strftime("%Y-%m")
date_list.append(date_str)
begin_date=add_months(begin_date,1)
returndate_list
defadd_months(dt,months):
month=dt.month-1+months
year=dt.year+month/12
month=month%12+1
day=min(dt.day,calendar.monthrange(year,month)[1])
returndt.replace(year=year,month=month,day=day)
defgetBetweenQuarter(begin_date):
quarter_list=[]
month_list=getBetweenMonth(begin_date)
forvalueinmonth_list:
tempvalue=value.split("-")
iftempvalue[1]in['01','02','03']:
quarter_list.append(tempvalue[0]+"Q1")
eliftempvalue[1]in['04','05','06']:
quarter_list.append(tempvalue[0]+"Q2")
eliftempvalue[1]in['07','08','09']:
quarter_list.append(tempvalue[0]+"Q3")
eliftempvalue[1]in['10','11','12']:
quarter_list.append(tempvalue[0]+"Q4")
quarter_set=set(quarter_list)
quarter_list=list(quarter_set)
quarter_list.sort()
returnquarter_list
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。