获取列表中两个日期时间之间的所有时间

时间:2016-11-26 06:29:08

标签: python datetime

我希望在两个日期之间得到所有时间。例如,我有两个日期时间

2016-10-15 12:15:572016-10-16 12:16:02

是否有最简单的方法可以找到如下所示的所有时间,

['2016-10-15 12:15:57','2016-10-15 12:15:58','2016-10-15 12:15:59','2016-10-15 12:16:00','2016-10-15 12:16:01','2016-10-15 12:16:02']

任何帮助都会非常感激

2 个答案:

答案 0 :(得分:3)

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr <= end:
        yield curr
        curr += delta

dtfmt = '%Y-%m-%d %H:%M:%S'

a = '2016-10-15 12:15:57'
b = '2016-10-15 12:16:02'

start = datetime.strptime(a,dtfmt)
end = datetime.strptime(b,dtfmt)

stack=[]
for result in perdelta(start , end, timedelta(seconds=1)):
    stack.append(str(result))

print(stack)

<强>输出

  

[&#39; 2016-10-15 12:15:57&#39;,&#39; 2016-10-15 12:15:58&#39;,&#39; 2016-10-15 12 :15:59&#39 ;,   &#39; 2016-10-15 12:16:00&#39;,&#39; 2016-10-15 12:16:01&#39;,&#39; 2016-10-15 12:16:02& #39]

答案 1 :(得分:0)

这可以帮到你:

import datetime

fmt = '%Y-%m-%d %H:%M:%S'

a = '2016-10-15 12:15:57'
b = '2016-10-15 12:16:02'

strp_a = datetime.datetime.strptime(a,fmt)
strp_b = datetime.datetime.strptime(b,fmt)

result = []

while strp_a <= strp_b:
    result.append(str(strp_a))
    strp_a += datetime.timedelta(seconds=1)



print(result)

输出:

['2016-10-15 12:15:57', '2016-10-15 12:15:58', '2016-10-15 12:15:59', 
'2016-10-15 12:16:00', '2016-10-15 12:16:01', '2016-10-15 12:16:02']