Skip to content Skip to sidebar Skip to footer

Formatting Time In Python?

How would I go about formatting time in Python? Lets say I have time = 9.122491 The time is in hours and I need to convert it to h:m format. So the desired output should be: 9:07

Solution 1:

Using the datetime module:

>>>from datetime import datetime, timedelta>>>mytime = 9.122491>>>temp = timedelta(hours=mytime)>>>print((datetime(1, 1, 1) + temp).strftime('%H:%M'))
09:07

Solution 2:

If you don't want to use a module, you can do it fairly simply like this:

>>>t = 9.122491>>>print'%d:%02d' % ( int(t), t%int(t)*60 )
9:07

%02d formats numbers to have leading zeros if they're less then 2 digits long

t%int(t) effectively gets rid of whole digits (11.111 becomes .111), then *60 converts the decimal fraction to minutes

Post a Comment for "Formatting Time In Python?"