Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Format a timedelta object

38 views
Skip to first unread message

Steven D'Aprano

unread,
May 26, 2016, 1:17:14 AM5/26/16
to
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?



--
Steve

Zachary Ware

unread,
May 26, 2016, 1:29:17 AM5/26/16
to
>>> timedelta(100)
datetime.timedelta(100)
>>> str(timedelta(seconds=100))
'0:01:40'
>>> str(timedelta(hours=100))
'4 days, 4:00:00'

(I recently spent *way* too long trying to figure out how to properly
format the thing before being reminded that a plain str call gives
exactly what I was after.)

--
Zach

Marko Rauhamaa

unread,
May 26, 2016, 1:43:24 AM5/26/16
to
Steven D'Aprano <steve+comp....@pearwood.info>:
>>> 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'

Steven D'Aprano

unread,
May 27, 2016, 12:22:11 PM5/27/16
to
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.



--
Steven

Zachary Ware

unread,
May 27, 2016, 12:35:16 PM5/27/16
to
On Fri, May 27, 2016 at 11:21 AM, Steven D'Aprano <st...@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....@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

Pete Forman

unread,
May 27, 2016, 4:41:40 PM5/27/16
to
It might be useful if timedelta were to get an isoformat() method. ISO
8601 specifies formats for durations; most people are familiar only with
the date amd time formats. There are variations available but PnDTnHnMnS
is probably the best. The biggest timedelta unit is days. Years and
months are not appropriate.

--
Pete Forman
0 new messages