Format a timedelta object

Marko Rauhamaa marko at pacujo.net
Thu May 26 01:43:08 EDT 2016


Steven D'Aprano <steve+comp.lang.python at pearwood.info>:

> I have a timedelta object, and I want to display it in a nice
> human-readable format like 03:45:17 for "three hours, forty five
> minutes, 17 seconds".
>
> Is there a standard way to do this?

   >>> import datetime
   >>> td = datetime.timedelta(hours=3, minutes=45, seconds=17)
   >>> d = datetime.datetime(2000, 1, 1)
   >>> (d + td).strftime("%T")
   '03:45:17'
   >>> "%02d:%02d:%02d" % (
   ...     td.seconds // 3600, td.seconds % 3600 // 60, td.seconds % 60)
   '03:45:17'



More information about the Python-list mailing list