# [Tutor] print question

Dick Moores rdm at rcblue.com
Tue Oct 9 07:33:03 CEST 2007

```Thanks, Kent and Ian. See below.

At 07:30 PM 10/8/2007, Kent Johnson wrote:

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

def secsToHMS(seconds):
"""
Convert seconds to hours:minutes:seconds, with seconds rounded
to hundredths of a second
"""
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
return "%02d:%02d:%2.2f" % (hours, minutes, seconds)

print secsToHMS(87154.04987)  --> 24:12:34.05  (what I wanted)

print secsToHMS(154.04987) --> 00:02:34.05 (what I wanted)

but
print secsToHMS(4.04987) --> 00:00:4.05 (I wanted 00:00:04.05)

I don't see how to get 00:00:04.05  using %f .
<http://www.python.org/doc/2.4.1/lib/typesseq-strings.html> is as clear as mud.

Dick

>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 at python.org
>>http://mail.python.org/mailman/listinfo/tutor
>

```