time conversion

F

flupke

Is there an easy to convert following hour notation hh:mm
to decimals?
For instance 2 hours and 30 minutes as 2:30 to 2,50
I don't really know where to search for this kind of conversion.

Thanks,
Benedict
 
F

flupke

flupke said:
Is there an easy to convert following hour notation hh:mm
to decimals?
For instance 2 hours and 30 minutes as 2:30 to 2,50
I don't really know where to search for this kind of conversion.

Thanks,
Benedict

I found a way. Not sure if it's the best:

time = "2:3"
factor = 100.0/60.0

time_parts = time.split(":")
minutes = int(float(time_parts[1]) * factor)
if ( len(str(minutes)) == 1 ): minutes *= 10 # to get 50 instead of 5
time_new = "%s,%.02s" % (time_parts[0],minutes)
print "%s -> %s " % (time,time_new)
 
F

Fredrik Lundh

flupke said:
Is there an easy to convert following hour notation hh:mm
to decimals?
For instance 2 hours and 30 minutes as 2:30 to 2,50
I don't really know where to search for this kind of conversion.

you mean like
2.5

?

</F>
 
S

Steven D'Aprano

Is there an easy to convert following hour notation hh:mm
to decimals?
For instance 2 hours and 30 minutes as 2:30 to 2,50
I don't really know where to search for this kind of conversion.


def str_HMS(s):
"""Convert a string "H:M:S" to a tuple of numbers (H, M, S).
H and M must be integers, S may be a float.
"""
L = s.split(":")
if len(L) < 3:
raise ValueError("Too few fields in H:M:S string.")
elif len(L) > 3:
raise ValueError("Too many fields in H:M:S string.")
H = int(L[0])
M = int(L[1])
S = float(L[2])
return (H, M, S)

def HMS_Seconds(hours, minutes, seconds):
"""Convert hours minutes seconds to seconds."""
return hours*60*60 + minutes*60 + seconds

def HMS_Hours(hours, minutes, seconds):
"""Convert hours minutes seconds to hours."""
return hours + minutes/60.0 + seconds/(60.0**2)

def Hours_HMS(h):
"""Convert time t in hours to hours minutes seconds."""
hours = int(t)
t = (t - hours)*60
minutes = int(t)
seconds = (t - minutes)*60
return (hours, minutes, seconds)

def Seconds_HMS(h):
"""Convert time t in seconds to hours minutes seconds."""
hours, t = divmod(t, 60*60)
minutes, seconds = divmod(t, 60)
return (hours, minutes, seconds)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,269
Messages
2,571,338
Members
48,026
Latest member
DannieKeeg

Latest Threads

Top