Reputation:
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)
Upvotes: 6
Views: 45777
Reputation: 1003
If you use datetime then I suggest:
>> import datetime
>> a = datetime.datetime.now()
datetime.datetime(2020, 5, 16, 11, 13, 59, 543985)
>> (a - datetime.datetime.combine(a.date(), datetime.time())).total_seconds() / 3600
11.233206662499999
Upvotes: 2
Reputation: 3805
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
Upvotes: 8