Dick Moores wrote:
> At 06:24 PM 10/8/2007, John Fouhy wrote:
>> On 09/10/2007, Dick Moores <[EMAIL PROTECTED]> wrote:
>>> What's the best way to get hours in 2 or more digits, and minutes in
>>> 2 digits, so that the above would be 05:07:36.88? (I'm writing a 
>> stopwatch.)
>>
>> String formatting!
>>
>>>>> template = '%02d:%02d:%02d.%02d'
>>>>> template % (1, 22, 3, 44)
>> '01:22:03.44'
> 
> Thanks!
> 
> So now I have
> 
> def secsToHMS(seconds):
>      """
>      Convert seconds to hours:minutes:seconds, with seconds rounded 
> to hundredths of a second, and print
>      """
>      hours, minutes = 0, 0
>      if seconds >= 60 and seconds < 3600:
>          minutes, seconds = divmod(seconds, 60)
>      elif seconds >= 3600:

You don't need this conditional, just use the next two lines 
unconditionally. If seconds<3600 it will still do the right thing.

>          hours, seconds = divmod(seconds, 3600)
>          minutes, seconds = divmod(seconds, 60)
>      seconds = str(round(seconds,2)).split('.')

You don't have to split the seconds, look at the %f formatting operator.

Kent

>      print seconds
>      print seconds[0]
>      hundredths = seconds[1]
>      print hundredths
> 
>      print "%02d:%02d:%02d.%02d" % (int(hours), int(minutes), 
> int(seconds[0]), int(seconds[1]))
> 
> secsToHMS(4789.3459876)
> 
> Which prints 01:19:49.35
> 
> Any improvements in the function to suggest?
> 
> Dick
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to