说我想查找两个日期之间的所有星期一,date_A
和date_B
from datetime import date, timedelta
days_to_substract = 50
date_A = date.today()-timedelta(days=days_to_subtract)
date_B = date.today()
我该怎么做?有没有办法在日期之间进行迭代?
答案 0 :(得分:2)
您可以使用生成器迭代日期范围:
def date_range(date1,date2):
while date1 < date2:
yield date1
date1 = date1 + timedelta(days=1)
并像这样迭代:
for dat in date_range(date_A,date_B):
<your code here>
答案 1 :(得分:1)
你的意思是这样吗?
def day_iter(start, end):
step = timedelta(days=1)
for i in range((end - start).days):
yield start + i*step
end = date.today()
start = end - timedelta(days=50)
for day in day_iter(start, end):
day.weekday() == 0:
print day.strftime("%A %Y-%m-%d")
输出:
Monday 2014-02-10
Monday 2014-02-17
Monday 2014-02-24
Monday 2014-03-03
Monday 2014-03-10
Monday 2014-03-17
Monday 2014-03-24
您也可以这样做:
today = date.today()
past = today - timedelta(50)
if past.weekday() != 0:
monday = past + timedelta(7 - past.weekday())
else:
monday = past
one_week = timedelta(7)
while monday < today:
print monday
monday += one_week
输出:
2014-02-10
2014-02-17
2014-02-24
2014-03-03
2014-03-10
2014-03-17
2014-03-24
你可以将它概括为这样的函数:
def past_weekdays(depth, weekday):
today = date.today()
past = today - timedelta(depth)
if past.weekday() != weekday:
past_day = past + timedelta((7 + (weekday - past.weekday())) % 7)
else:
past_day = past
one_week = timedelta(7)
while past_day < today:
yield past_day
past_day += one_week
答案 2 :(得分:1)
从当前日期查找上周一,并根据7天差异查找剩余时间:
from datetime import date, timedelta
days_to_substract = 50
date_A = date.today()-timedelta(days=days_to_substract)
date_B = date.today()
cDay = date_B - timedelta(days=date_B.weekday())
print cDay
while cDay > date_A:
cDay = cDay - timedelta(days=7)
print cDay
输出:
2014-03-24
2014-03-17
2014-03-10
2014-03-03
2014-02-24
2014-02-17
2014-02-10
2014-02-03
答案 3 :(得分:1)
也许这个:
from datetime import date, timedelta
days_to_substract = 50
date_A = date.today()-timedelta(days=days_to_substract)
date_B = date.today()
date_tmp = date_A
numOfMondays = 0
deltaStep = 1
while date_tmp < date_B:
if date_tmp.strftime("%A") != "Monday":
print("Date before first monday {}".format(date_tmp))
date_tmp += timedelta(days=1)
else:
print("Monday : {}".format(date_tmp))
date_tmp += timedelta(days=7)
numOfMondays += 1
print("from {} to {} there are {} monday".format(date_A, date_B, numOfMondays))
带输出
Date before first monday 2014-02-05
Date before first monday 2014-02-06
Date before first monday 2014-02-07
Date before first monday 2014-02-08
Date before first monday 2014-02-09
Monday : 2014-02-10
Monday : 2014-02-17
Monday : 2014-02-24
Monday : 2014-03-03
Monday : 2014-03-10
Monday : 2014-03-17
Monday : 2014-03-24
from 2014-02-04 to 2014-03-26 there are 7 monday