Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading