Format a timedelta object

Zachary Ware zachary.ware+pylist at gmail.com
Fri May 27 12:34:36 EDT 2016


On Fri, May 27, 2016 at 11:21 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, 26 May 2016 03:28 pm, Zachary Ware wrote:
>> On Thu, May 26, 2016 at 12:16 AM, Steven D'Aprano
>> <steve+comp.lang.python at pearwood.info> wrote:
>>> 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".
>>
>>    >>> str(timedelta(seconds=100))
>>    '0:01:40'
>
> Thanks Zach. Unfortunately, the format is not quite how I want it, so I
> guess I'll have to extract the H:M:S fields manually from the seconds.

What's missing the mark, no leading 0 on the hour, or the extra 0 hour
specification?

Yes, unfortunately it looks like manual extraction is your only option
for that.  I'd support an RFE for a strftime-like __format__ method on
timedelta that only supported certain %-codes, though.  I haven't
checked to see if there's already an open issue.

-- 
Zach



More information about the Python-list mailing list