[Tutor] Formatting timedelta objects

wesley chun wescpy at gmail.com
Tue Dec 11 00:16:45 CET 2007


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


hi noufal,

there's no real easy way to do this since only date, datetime, and
time objects in datetime have strftime() methods.  timedelta objects
only give you days, seconds, and microseconds, so you have to roll
your own:

>>> z # some random timedelta object
datetime.timedelta(1, 84830, 429624)
>>> str(z)
'1 day, 23:33:50.429624'
>>> sec = z.days*24*60*60+z.seconds
>>> min, sec = divmod(sec, 60)
>>> hrs, min = divmod(min, 60)
>>> hrs, min, sec
(47, 33, 50)
>>> '%02d:%02d:%02d' % (hrs, min, sec)
'47:33:50'

if you want to round with microseconds, you'll have to add that to the
mix above.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list