本文介绍了打印两个日期之间的所有日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
from datetime import date
d1 = date(2008,8,15)
d2 = date(2008,9,15)
我在寻找简单的代码打印中间的所有日期:
I'm looking for simple code to print all dates in-between:
2008,8,15
2008,8,16
2008,8,17
...
2008,9,14
2008,9,15
感谢
推荐答案
我想出了这一点:
from datetime import date, timedelta
d1 = date(2008, 8, 15) # start date
d2 = date(2008, 9, 15) # end date
delta = d2 - d1 # timedelta
for i in range(delta.days + 1):
print(d1 + timedelta(days=i))
输出:
2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15
您的问题要求日期之间,但我相信你的意思是包括th e开始和结束点,所以它们被包括在内。要删除结束日期,请删除for循环末尾的+1。要删除开始日期,请在范围函数的开头添加1。
Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the +1 at the end of the for loop. To remove the start date, add a 1 to the beginning of the range function.
这篇关于打印两个日期之间的所有日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!