Convert fraction of hour to hh:mm:ss

Asked

Viewed 895 times

1

My hourly data set is stored in the time = [0 variable. , 0.08333333, 0.16666667, 0.25, 0.333333, 0.41666667, 0.5 , 0.58333333, 0.666667, 0.75, 0.83333333, 0.91666667, 1. , 08333333, 1.16666667]

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

I tried to create a function, but this 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'

  • Doing this, another error appears: Attributeerror: type Object 'datetime.time' has no attribute 'time'

1 answer

2


This error is happening because the divmod that you are calling does not return a number - to have a split rest in Python, simply use the operator % . Divmod returns the entire part and the rest of the division - but that’s not why all the 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" (because it’s not, it’s very rational), and you’ll get the expected result - later on, as you have more resourcefulness, you can worry about wanting to shorten the lines of code:

minutes = time // 60
seconds = time % 60

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

(the // is the "integer" split operator that truncates the result).

Also, another problem that you have more down is trying to create a datetime.datetime by spending 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 you wish with other objects.

And finally, not directly related to your problem - but you shouldn’t be using Python 2.7 anymore - in less than two years this version will be completely without support of any kind - it’s been almost 10 years since it was released. 3.x versions of python are current and have various facilities and new features.

  • Thank you! I made some changes here, and now it’s working...regarding the use of python, I was using version 3.6, but I had problems, I used to brake frequently and so I ended up going back to the older version but surely, at some point, I’ll end up coming back to it again

Browser other questions tagged

You are not signed in. Login or sign up in order to post.