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

Ricardo Aráoz ricaraoz at gmail.com
Wed Dec 11 17:21:10 CET 2013


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'
 >>>



More information about the Tutor mailing list