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
255 views
in Technique[技术] by (71.8m points)

python - Converting time to a float

I wrote a program to compute the hours I've worked but at the end, it returns the value as a time.

EX: I worked from 11:45 to 4:30. My program returns 4:45 I would like it to return 4.75.

How do I convert this?

I am using the following code:

import datetime as dt

from datetime import timedelta

start =(input("Enter start time: " ))
end =(input("Enter start time: " ))
start_dt = dt.datetime.strptime(start, '%H:%M')
end_dt = dt.datetime.strptime(end, '%H:%M')
time =(end_dt - start_dt)
if time.days < 0:
    time=timedelta(days=0,seconds=time.seconds,microseconds=time.microseconds)
    time= str(time)
    time2=dt.datetime.strptime(time, '%H:%M:%S') 
    off_set=dt.datetime.strptime('12:00:00', '%H:%M:%S')
    time= time2 - off_set 

print (time)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you use a datetime, the hour and minute method should give you what you want

>>>a=datetime.datetime.now().time()
>>>a
datetime.time(21, 17, 35, 562000) 
>>>a.hour+a.minute/60.0
21.283333333333335

If you are using a timedelta (as is the case in your code), you should use :

mytimedelta = atime - anothertime
secs=mytimedelta.seconds #timedelta has everything below the day level stored in seconds
minutes = ((secs/60)%60)/60.0
hours = secs/3600
print hours + minutes

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

...