Prev: CRC16
Next: triangulation
From: flupke on
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
From: flupke on
flupke wrote:
> 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)
From: Fredrik Lundh on
"flupke" wrote:

> 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

>>> timestamp = "2:30"
>>> hour, minute = timestamp.split(":")
>>> print int(hour) + int(minute) / 60.0
2.5

?

</F>



From: flupke on
Fredrik Lundh wrote:
> "flupke" wrote:
>
>
>>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
>
> >>> timestamp = "2:30"
> >>> hour, minute = timestamp.split(":")
> >>> print int(hour) + int(minute) / 60.0
> 2.5
>
> ?
>
> </F>
>
>
>
yep, your sollution is shorter so i'll use that :)

Thanks
Benedict
From: Steven D'Aprano on
On Thu, 27 Oct 2005 14:36:30 +0000, flupke wrote:

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



--
Steven.

 | 
Pages: 1
Prev: CRC16
Next: triangulation