Sakeer
Sakeer

Reputation: 2006

Get all the times in between two datetime in list

I want to get all the times in between two datetime. For example i have two datetime

2016-10-15 12:15:57 and 2016-10-16 12:16:02

Is there any easiest way to find all the times like below,

['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']

Any help would be really appreciated

Upvotes: 0

Views: 2892

Answers (2)

Rohan Khude
Rohan Khude

Reputation: 4893

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)

OUTPUT

['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']

Upvotes: 5

Ahasanul Haque
Ahasanul Haque

Reputation: 11134

This should help you:

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)

Output:

['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']

Upvotes: 0

Related Questions