Formatting time in Python?

醉酒当歌 提交于 2019-12-12 19:34:11

问题


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!


回答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



回答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



来源:https://stackoverflow.com/questions/19215263/formatting-time-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!