如何通过添加 7 天来创建从 x 日期到 y 日期的天数列表?
我尝试了此代码,但是在检查列表长度时什么也没有显示
from datetime import date
from datetime import timedelta
sdate= date(1990,10,25)
tdate=date(1990,10,25)
i=7
rqd_dt=[]
adate = date(2022,12,31)
while adate > tdate:
rqd_dt.append(tdate)
tdate = sdate+timedelta(days=i)
print(len(rqd_dt))
I have tried this code but showing nothing while checking the list length
from datetime import date
from datetime import timedelta
sdate= date(1990,10,25)
tdate=date(1990,10,25)
i=7
rqd_dt=[]
adate = date(2022,12,31)
while adate > tdate:
rqd_dt.append(tdate)
tdate = sdate+timedelta(days=i)
print(len(rqd_dt))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你只是犯了一个小错误。更改此行:
tdate = sdate+timedelta(days=i)
到
tdate = tdate+timedelta(days=i)
这样,
tdate
就会不断增加 7 天。正如您所看到的,tdate
在每个循环中都保持相同,因此它不会卡在 print 语句中 - 它会卡在无限循环中。如果您在while
循环中添加了一些调查性打印语句,您会看到这一点。You have a small mistake only. Change this line:
tdate = sdate+timedelta(days=i)
to
tdate = tdate+timedelta(days=i)
This way,
tdate
keeps incrementing by 7 days. As you had it,tdate
remains the same every loop, so it's not stuck at the print statement - it's stuck in an infinite loop. If you added a little investigative print statement inside yourwhile
loop, you would see this.