user1804933
user1804933

Reputation: 453

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

Any help would be greatly appreciated!

Upvotes: 3

Views: 405

Answers (2)

Jollywatt
Jollywatt

Reputation: 1365

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

Upvotes: 1

TerryA
TerryA

Reputation: 59974

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

Upvotes: 4

Related Questions