Home > Blockchain >  How to calculate a time interval in seconds between two times (inclusive) in python?
How to calculate a time interval in seconds between two times (inclusive) in python?

Time:06-22

I need to calculate a time interval in seconds between two times (inclusive) and return the result as a list: e.g.

t1 = datetime.now()
# some code
t2 = datetime.now()

start_time = t1.strftime("%H:%M:%S") # 15:20:30
end_time = t2.strftime("%H:%M:%S")   # 15:20:33

def get_time_interval(s_time, e_time):
    # TODO

time_interval = get_time_interval(t1, t2)
print(time_interval) # ['15:20:30', '15:20:31', '15:20:32', '15:20:33']

Is there an elegant way to solve this or do I have to calculate the difference between start and end and add every second in a loop on the start time (e.g. with timedelta(seconds=i)?

CodePudding user response:

It's probably an overkill but pandas has date_range method that lets you specify start, end times and frequency and returns a range of datetimes:

from datetime import datetime
import time
import pandas as pd
t1 = datetime.now()
time.sleep(3)
t2 = datetime.now()

def get_time_interval(s_time, e_time):
    return pd.date_range(s_time, e_time, freq='S').strftime("%H:%M:%S").tolist()

time_interval = get_time_interval(t1, t2)
print(time_interval) # ['22:16:31', '22:16:32', '22:16:33', '22:16:34']
  • Related