于我需求而言,我只需要用到fixed_interval、weekly、per_month三個(gè)方法返回的回歸間隔列表就行,最后的這個(gè)make_date_from_list方法,是為了能在這里展示效果
class GetStrategyDedail:
today = datetime.date.today()
def __init__(self, begin_date, end_date):
self.begin_date = datetime.datetime.strptime(begin_date, "%Y-%m-%d")
self.end_date = datetime.datetime.strptime(end_date, "%Y-%m-%d")
def fixed_interval(self, num):
"""
固定間隔的類型,直接使用間隔數(shù)字
:param num:間隔的天數(shù)
:return:不同時(shí)間段內(nèi),對(duì)應(yīng)策略的執(zhí)行時(shí)間間隔列表
"""
detail_list = list()
date_num = (self.end_date - self.begin_date).days
for i in range(num, date_num+1, num):
detail_list.append(i)
detail_list.insert(0, 0)
return detail_list
def weekly(self, i, weeks=1):
"""
每周xx,每月xx的數(shù)據(jù)類型
:param i:0-星期一,1-星期二,2-星期三,3-星期四,4-星期五,5-星期六,6-星期日
:param weeks:間隔周數(shù),默認(rèn)間隔一周
:return:不同時(shí)間段內(nèi),對(duì)應(yīng)策略的執(zhí)行時(shí)間間隔列表
"""
while self.begin_date.weekday() != i:
self.begin_date += datetime.timedelta(days=1)
num = (self.begin_date.date() - self.today).days
fixed_list = self.fixed_interval(weeks * 7)
fixed_list.insert(0, num)
return fixed_list
def per_month(self, date):
"""
date:指定要獲取的每個(gè)月的日期
:return:不同時(shí)間段內(nèi),對(duì)應(yīng)策略的執(zhí)行時(shí)間間隔列表
"""
date_list = list()
specific_list = list()
year = self.begin_date.year
begin_month = self.begin_date.month
end_month = self.end_date.month
day = self.end_date.day
while begin_month = end_month:
designated_date = f'{year}-{begin_month}-{date}'
date_list.append(datetime.datetime.strptime(designated_date, "%Y-%m-%d"))
begin_month += 1
for specific_date in date_list:
num = (specific_date.date() - self.today).days
if num > 0:
specific_list.append(num)
if day date:
specific_list.pop()
return specific_list
def make_date_from_list(self, num, interval=1, mode='day'):
"""
:param interval: 間隔的周數(shù),默認(rèn)為1(每周)
:param num:根據(jù)mode來區(qū)分,分表代表:間隔的天數(shù),周幾(0-6/周一-周日),指定的月日期
:param mode:day, week, month
:return: 不同時(shí)間段內(nèi),對(duì)應(yīng)策略的執(zhí)行時(shí)間間隔列表
"""
date_list = list()
if mode == 'day':
details_list = self.fixed_interval(num)
elif mode == 'week':
details_list = self.weekly(num, interval)
elif mode == 'month':
details_list = self.per_month(num)
first_date = self.today + datetime.timedelta(details_list[0])
if mode == 'day':
for i in details_list:
date = self.begin_date.date() + datetime.timedelta(i)
date_list.append(date.isoformat())
elif mode == 'month':
for i in details_list:
date = self.today + datetime.timedelta(i)
date_list.append(date.isoformat())
else:
for i in details_list[1:]:
date = first_date + datetime.timedelta(i)
date_list.append(date.isoformat())
return date_list
到此這篇關(guān)于python獲取指定時(shí)間段內(nèi)特定規(guī)律的日期列表的文章就介紹到這了,更多相關(guān)python獲取指定時(shí)間段內(nèi)日期列表內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!