获取一周中最后一个星期日与今天之间的日期列表

时间:2019-11-04 05:24:43

标签: python python-3.x datetime

我想要一个列表包含一周中最后一个星期日到今天之间的所有日期,例如今天是05/11/2019,最后一个星期日是03/11/2019,我想列出所有在03/11/2019之间的日期今天是05/11/2019

我可以使用下面的代码获取一周中的最后一个星期日

from datetime import datetime, timedelta, date

today = date.today()
offset = (today.weekday() - 6) % 7
print("Offset", offset)
last_sunday = today - timedelta(days=offset)
print(last_sunday) 

我想要的输出是

['03/11/2019', '04/11/2019', '05/11/2019']

3 个答案:

答案 0 :(得分:1)

这里。希望这会对您有所帮助!

from datetime import datetime, timedelta, date

def daterange(date1, date2):
    for n in range(int ((date2 - date1).days)+1):
        yield date1 + timedelta(n)

today = date.today()
offset = (today.weekday() - 6) % 7
print("Offset", offset)
last_sunday = today - timedelta(days=offset)
print(last_sunday)

for dt in daterange(last_sunday, today):
    print(dt.strftime("%Y-%m-%d"))

答案 1 :(得分:1)

from datetime import date, timedelta

sdate = date(2019,11,3)
today = date.today()
diff = today - sdate
for i in range(diff.days+1):
    day = sdate + timedelta(days=i)
    print(day)

答案 2 :(得分:1)

使用您指定的输出格式的解决方案。

from datetime import datetime, timdelta 
current_date = datetime.now()-timedelta(days=1)
datetime_list = [current_date-timedelta(days=offset) for offset in range((current_date.weekday()+1)%7+1)]
datetime_list.reverse()
datetime_list = [ '{0:02d}/{1:02d}/{2:}'.format(i.day,i.month,i.year) for i in datetime_list]
print(datetime_list)