[Tutor] Formatting timedelta objects

John Fouhy john at fouhy.net
Tue Dec 11 00:14:18 CET 2007


On 11/12/2007, Noufal Ibrahim <noufal at airtelbroadband.in> wrote:
> Hello everyone,
>    This is probably something simple but I can't seem to find a way to
> format a timedelta object for printing? I need to be able to print it in
> a HH:MM:SS format but without the microseconds part (which is what you
> get if you str() it).
>
>    Any pointers?

datetime.timedelta have 'days', 'seconds' and 'microseconds'
attributes.  You could write your own formatter using the seconds
attribute.

e.g.:

def formatTD(td):
  hours = td.seconds // 3600
  minutes = (td.seconds % 3600) // 60
  seconds = td.seconds % 60
  return '%s:%s:%s' % (hours, minutes, seconds)

HTH!

-- 
John.


More information about the Tutor mailing list