Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datetime - Converting decimal time (HH.HHH) into HH:MM:SS in Python

I have hours in this format,

72.345, 72.629, 71.327, ...

as a result of performing a calculation in Python. It seems that the simplest way to convert these into HH:MM:SS format is using the datetime module like this:

time = str(datetime.timedelta(seconds = 72.345*3600))

However, that returns a values with days, which I don't want:

'3 days, 0:20:42'

This is the best way my brain came up with the final values I want:

str(int(math.floor(time))) + ':' + str(int((time%(math.floor(time)))*60)) + ':' + str(int(((time%(math.floor(time)))*60) % math.floor(((time%(math.floor(time)))*60))*60))

Which is ridiculously long and probably unnecessary. But it does give me the answer I want:

'72:20:41'

Are there better methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You do not have to use datetime. You can easily compute hours, minutes and seconds from your decimal time.

You should also notice that you can use string formatting which is really easier to use than string concatenation.

time = 72.345

hours = int(time)
minutes = (time*60) % 60
seconds = (time*3600) % 60

print("%d:%02d.%02d" % (hours, minutes, seconds))
>> 72:20:42

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...