4

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
  • it is still not clear which value you want to set in this format : your code does not return or print anything – WNG Oct 31 '17 at 20:57
  • FYI, this line `time.seconds/60` does absolutely nothing. – Robᵩ Oct 31 '17 at 22:30
  • 6
    Please do not vandalize your question. Thank you. – K.Dᴀᴠɪs Mar 02 '18 at 21:11
  • 5
    Please don't make more work for people by vandalizing your posts. By posting on the Stack Exchange (SE) network, you've granted a non-revocable right, under the [CC BY-SA 3.0 license](https://creativecommons.org/licenses/by-sa/3.0), for SE to distribute that content (i.e. regardless of your future choices). By SE policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. – Makyen Mar 02 '18 at 21:16
  • 2
    Don't want a question associated to your account? https://meta.stackexchange.com/a/96746 – LW001 Mar 02 '18 at 21:24

2 Answers2

7

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
WNG
  • 3,705
  • 2
  • 22
  • 31
1

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
Karel Marik
  • 811
  • 8
  • 13