[Tutor] print question

Dick Moores rdm at rcblue.com
Tue Oct 9 04:15:44 CEST 2007


At 06:24 PM 10/8/2007, John Fouhy wrote:
>On 09/10/2007, Dick Moores <rdm at rcblue.com> 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:
         hours, seconds = divmod(seconds, 3600)
         minutes, seconds = divmod(seconds, 60)
     seconds = str(round(seconds,2)).split('.')
     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




More information about the Tutor mailing list