问题
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)
回答1:
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
来源:https://stackoverflow.com/questions/47043841/converting-time-to-a-float