443,908 Members | 1,838 Online
Need help? Post your question and get tips & solutions from a community of 443,908 IT Pros & Developers. It's quick & easy.

time conversion

 P: n/a 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 Oct 27 '05 #1
4 Replies

 P: n/a 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) Oct 27 '05 #2

 P: n/a "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 ? Oct 27 '05 #3

 P: n/a Fredrik Lundh wrote: "flupke" wrote:Is there an easy to convert following hour notation hh:mmto decimals?For instance 2 hours and 30 minutes as 2:30 to 2,50I 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 ? yep, your sollution is shorter so i'll use that :) Thanks Benedict Oct 27 '05 #4

 P: n/a 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. Oct 27 '05 #5