[Tutor] print question

Ian Witham witham.ian at gmail.com
Tue Oct 9 03:27:33 CEST 2007


On 10/9/07, Dick Moores <rdm at rcblue.com> wrote:
>
> def secsToHMS(seconds):
>      """
>      Convert seconds to hours:minutes:seconds, with seconds rounded
> to nearest 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))
>      print "%d:%d:%s" % (int(hours), int(minutes), seconds)
>
> secsToHMS(18456.876012)
>
> This prints 5:7:36.88
>
> 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.)



The string formatting operators you have used ("%d:%d:%s") can be altered
with certain flags to give you the desired output.

The relevant documentation is
here<http://www.python.org/doc/2.1.3/lib/typesseq-strings.html>
The example near the top of the page shows how to pad the output with
leading zeros.


Good luck.

Ian.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071009/d76f98ae/attachment-0001.htm 


More information about the Tutor mailing list