[Tutor] formatting datetime.timedelta to "HH:MM:SS"

Jignesh Sutar jsutar at gmail.com
Wed Dec 11 18:40:13 CET 2013


Thanks folks, I think I have this as a working solution:

import datetime, time
a= datetime.datetime.now()
time.sleep(7.1564651443644)
b= datetime.datetime.now()
#for testing longer time periods
#a= datetime.datetime(2003, 8, 4, 8, 31, 4,0)
#b= datetime.datetime(2004, 8, 5, 19, 32, 6,0)
c = b-a
print "%s days, %.2dh: %.2dm: %.2ds" %
(c.days,c.seconds//3600,(c.seconds//60)%60, c.seconds%60)

The attributes for timedelta seem only to be days, seconds and microseconds
only. Nonetheless these can be used to deduce HH:MM:SS.

Thanks,
Jignesh


On 11 December 2013 16:21, Ricardo Aráoz <ricaraoz at gmail.com> wrote:

> El 11/12/13 10:37, Mark Lawrence escribió:
>
>  On 11/12/2013 13:12, Jignesh Sutar wrote:
>>
>>>     print str(exe_time).split('.')[0]
>>> Sorry, I guess my question was why I can't use something similar to
>>> below on exe_time (of type datetime.timedelta)? Rather than doing string
>>> manipulation on decimals or colons to extract the same.
>>>
>>> now = datetime.now()
>>> print now.hour
>>> print now.minute
>>> print now.year
>>>
>>>
>> Old style
>>
>> print('%02d:%02d:%04d' % (now.hour, now.minute, now.year))
>>
>> New style
>>
>> print('{}:{}:{}'.format(now.hour, now.minute, now.year))
>>
>> Sorry I can never remember the formatting types to go between {} so look
>> for them around here http://docs.python.org/3/library/string.html#
>> formatstrings
>>
>>
>
> Or just use strftime() :
>
> >>> import datetime
> >>> n = datetime.datetime.now()
> >>> n.strftime('%H:%M:%S')
> '13:19:04'
>
> >>>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131211/a8115baa/attachment-0001.html>


More information about the Tutor mailing list