How to get a set of all time between range of start and end time?


I want to get all the time between start time and end time in python, so I was using for loop with range function.

There are 2 variables, a and b which have time in %H:%M:%S format.

These 2 variables are start and end time and I want to print all the time between the start and end time.

import datetime
from datetime import datetime
import time

a = '20:15:16'
b = '20:32:55'

a = datetime.strptime(a,'%H:%M:%S').time()
b = datetime.strptime(b,'%H:%M:%S').time()

for i in range(a,b):

For this I am getting an error – datetime.time' object cannot be interpreted as an integer.

I want to print all the time between a and b.


There are infinite moments between two times. I think you might be asking, "How can I print a timestamp for every second or every minute between A and B?"

I don’t think you want to be using the range function. The error you are seeing is because range expects integers as input, not whole datetime objects.

Here is something that may do what you want:

from datetime import datetime, timedelta

# Define our times
str_A = '20:15:16'
str_B = '20:32:55'

# Create our datetime objects
A = datetime.strptime(str_A,'%H:%M:%S')
B = datetime.strptime(str_B,'%H:%M:%S')

# Create a loop where you print a time, starting with time A
# and then increase the time stamp by some value, in this case,
# 1 minute, until you reach time B
tmp = a
while tmp <= b:
    tmp = tmp + timedelta(minutes=1)

Please notice the line,


where we only extract the time part when we need it, leaving the object as a datetime object for easy manipulation.

I used this question for reference:
What is the standard way to add N seconds to datetime.time in Python?

So this question is really adorable. There is something about reading, ‘I need to print "all the time" between these two times’ that gives me joy.

Answered By – Acceptance

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.