打印两个日期之间的所有日期

时间:2011-09-01 17:44:08

标签: python datetime

例如:

from datetime import date

d1 = date(2008,8,15)
d2 = date(2008,9,15)

我正在寻找简单的代码来打印中间的所有日期:

2008,8,15  
2008,8,16  
2008,8,17  
...  
2008,9,14  
2008,9,15

由于

5 个答案:

答案 0 :(得分:256)

我想出了这个:

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

你的问题要求中间的日期,但我相信你的意思是包括起点和终点,所以它们都包括在内。要删除结束日期,请删除for循环结束时的+1。要删除开始日期,请在范围函数的开头添加1。

答案 1 :(得分:27)

使用列表理解:

from datetime import date, timedelta

d1 = date(2008,8,15)
d2 = date(2008,9,15)

# this will give you a list containing all of the dates
dd = [d1 + timedelta(days=x) for x in range((d2-d1).days + 1)]

for d in dd:
    print d

# you can't join dates, so if you want to use join, you need to
# cast to a string in the list comprehension:
ddd = [str(d1 + timedelta(days=x)) for x in range((d2-d1).days + 1)]
# now you can join
print "\n".join(ddd)

答案 2 :(得分:8)

基本上与Gringo Suave的答案相同,但是使用生成器:

from datetime import datetime, timedelta


def datetime_range(start=None, end=None):
    span = end - start
    for i in xrange(span.days + 1):
        yield start + timedelta(days=i)

然后您可以按如下方式使用它:

In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out: 
[datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 1, 2, 0, 0),
 datetime.datetime(2014, 1, 3, 0, 0),
 datetime.datetime(2014, 1, 4, 0, 0),
 datetime.datetime(2014, 1, 5, 0, 0)]

或者像这样:

In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
   ...:     print date
   ...:     
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00

答案 3 :(得分:6)

import datetime

d1 = datetime.date(2008,8,15)
d2 = datetime.date(2008,9,15)
diff = d2 - d1
for i in range(diff.days + 1):
    print (d1 + datetime.timedelta(i)).isoformat()

答案 4 :(得分:2)

import datetime

begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)

next_day = begin
while True:
    if next_day > end:
        break
    print next_day
    next_day += datetime.timedelta(days=1)