Converting a float to hh:mm format
Alternatively to using datetime
, you can just use simple formatting with a bit of maths, eg:
result = '{0:02.0f}:{1:02.0f}'.format(*divmod(time * 60, 60))
(This assumes that time
is nonnegative.)
Using datetime.timedelta
:
>>> import datetime
>>> datetime.timedelta(hours=9.888888888888886)
datetime.timedelta(0, 35600)
>>> str(datetime.timedelta(hours=9.888888888888886))
'9:53:20'
>>> str(datetime.timedelta(hours=9.888888888888886)).rsplit(':', 1)[0]
'9:53'
>>> datetime.datetime.combine(datetime.date.today(), datetime.time()) + \
... datetime.timedelta(hours=9.888888888888886)
datetime.datetime(2014, 12, 16, 9, 53, 20)
>>> _.strftime('%H:%M')
'09:53'
Using divmod you get the remainder and the quotient of a division.
minutes = 9.888888888888886*60
hours, minutes = divmod(minutes, 60)
print "%02d:%02d"%(hours,minutes)
Output:
09:53
If you want the seconds too:
seconds = 9.888888888888886*60*60
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print "%02d:%02d:%02d"%(hours,minutes,seconds)