Convert fraction of time in the format hh: mm: ss

1

My time data set is stored in the variable time = [0., 0.08333333, 0.16666667, 0.25, 0.33333333, 0.41666667, 0.5, 0.58333333, 0.66666667, 0.75, 0.83333333, 0.91666667, 1., 08333333, 1.16666667] p>

Can anyone tell me if there is a simple way to convert this to the format hh: mm: ss?

I tried to create a function, but it is giving error:

import datetime as dt
from datetime import timedelta

def time2dt(time):

    seconds = int(time*60*60)
    minutes, seconds = int(divmod(seconds, 60))
    hours, minutes = int(divmod(minutes, 60))
    return dt.datetime(hours, minutes, seconds) + dt.timedelta(time % 1)

    dates   = [time2dt(time[i]) for i in np.arange(len(time))]
    datestr = [i.strftime('%H:%M:%S') for i in dates]

TypeError: int () argument must be a string or a number, not 'tuple'

    
asked by anonymous 05.02.2018 / 16:25

1 answer

2

This error is happening because the divmod you are calling does not return a number - to have a remainder of division in Python, simply use the % operator. Divmod returns the whole part and the rest of the division - but that is not why all other functions (the "int" in particular) will be able to work automatically with a sequence.

Do the program in parts, without waiting for the language to be "magic" (why it is not, it is very rational), and you will have the expected result - later, as you have more worrying about wanting to shorten the lines of code:

minutes = time // 60
seconds = time % 60

instead of the wrong minutes, seconds = int(divmod(time, 60)) you have there.

( // is the integer division operator that truncates the result).

In addition, another downside problem is that you try to create a datetime.datetime by passing only hours, minutes, and seconds: datetimes need the day, month, and year. - create an object datetime.time with day, month and year, and then yes, combine as desired with other objects.

And finally, not directly related to your problem - but you should no longer be using Python 2.7 - in less than two years this version will be completely unsupported of any kind - almost 10 years ago it was released. Python 3.x versions are current and have various features and new features.

    
05.02.2018 / 17:41