gregory gregory - 3 months ago 8
Python Question

Express time elapsed between element of an array of date in hour min second using python

I have a list of time creation of files obtained using os.path.getmtime

time_creation_sorted
Out[45]:
array([ 1.47133334e+09, 1.47133437e+09, 1.47133494e+09,
1.47133520e+09, 1.47133577e+09, 1.47133615e+09,
1.47133617e+09, 1.47133625e+09, 1.47133647e+09])


I know how to convert those elements in hour minute seconds.

datetime.fromtimestamp(time_creation_sorted[1]).strftime('%H:%M:%S')
Out[62]: '09:59:26'


What I would like to do is to create another table that contains the time elapsed since the first element but expressed in hour:min:sec such that it would look like:

array(['00:00:00','00:16:36',...])


But I have not manage to find how to do that. Taking naively the difference between the elements of time_creation_sorted and trying to convert to hour:min:sec does not give something logical:

datetime.fromtimestamp(time_creation_sorted[1]-time_creation_sorted[0]).strftime('%H:%M:%S')
Out[67]: '01:17:02'


Any idea or link on how to do that?

Thanks,
Grégory

Answer

You need to rearrange some parts of your code in order to get the desired output.

First you should convert the time stamps to datetime objects which differences result into so called timedelta objects. The __str__() representation of those timedelta objects are exactly what you want:

from datetime import datetime

tstamps = [1.47133334e+09, 1.47133437e+09, 1.47133494e+09, 1.47133520e+09, 1.47133577e+09, 1.47133615e+09, 1.47133617e+09, 1.47133625e+09, 1.47133647e+09]
tstamps = [datetime.fromtimestamp(stamp) for stamp in tstamps]

tstamps_relative = [(t - tstamps[0]).__str__() for t in tstamps]
print(tstamps_relative)

giving:

['0:00:00', '0:17:10', '0:26:40', '0:31:00', '0:40:30', '0:46:50', '0:47:10', '0:48:30', '0:52:10']
Comments