Deren Devrimol
Deren Devrimol

Reputation: 19

Converting Time Output to a Float Variable (Python)

from Tkinter import *
from datetime import datetime
from datetime import timedelta
import math

rate1 = str(35.34) 
amp = 2.40
pmp = 2.50



signOnSun1 = raw_input("What time did you sign on Sunday: ");
signOffSun1 = raw_input("What time did you sign off Sunday: ");

if (signOnSun1 < 0600):
    rate1 = rate1 + amp
elif (signOnSun1 > 1100):
    rate1 = rate1 + pmp
elif (signOffSun1 > 1800):
    rate1 = rate1 + pmp
else:
    rate1 = 35.34

FMT = '%H%M'    
timeWorkedSun1 =  ( (datetime.strptime(signOffSun1, FMT)) -  (datetime.strptime   (signOnSun1, FMT)))

* I want to convert timeWorkedSun1 to a float so i can multiply it with rate1 but it seems to be the bane of my life. Any ideas?*

Upvotes: 0

Views: 5609

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881555

timeWorkedSun1 is of type datetime.timedelta. Call its total_seconds method to translate it into a number of second (then divide by 3600 to get it in hours-and-fractions). I.e:

time_mul_by_hourly_rate = (timeWorkedSun1.total_seconds() / 3600.0) * rate1

Upvotes: 3

Gagravarr
Gagravarr

Reputation: 48326

Assuming what you want to do is ask a user to enter two hours:minutes figures, and calculate the hours + fractions of hours between them, then using datetime as you do now, you'd do something like (simplified):

signOn = "09:15"
signOff = "15:45"

FMT = "%H:%M"
timeWorkedSun =  datetime.strptime(signOff, FMT) -  datetime.strptime(signOn, FMT)

# timeWorkedSun is now a datetime.timedelta
fractionHours = timeWorkedSun.total_seconds()/60.0/60

Alternately, without datetime code, we could do:

signOn = "09:15"
signOff = "15:45"

signOnP = [int(n) for n in signOn.split(":")]
signOffP = [int(n) for n in signOff.split(":")]

signOnH = signOnP[0] + signOnP[1]/60.0
signOffH = signOffP[0] + signOffP[1]/60.0

hours = signOffH - signOnH

However, that'll fail if someone started at 6pm on one day and ended at 3am the next day, so you might want to rethink your logic

Upvotes: 1

Related Questions