将时间输出转换为浮点变量(Python)

时间:2014-12-20 05:35:18

标签: python datetime floating-point

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)))

*我想将timeWorkedSun1转换为浮点数,所以我可以将它与rate1相乘,但这似乎是我生命中的祸根。有什么想法吗?*

2 个答案:

答案 0 :(得分:3)

timeWorkedSun1的类型为datetime.timedelta。调用它的total_seconds方法将其转换为秒数(然后除以3600以得到小时和分数)。即:

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

答案 1 :(得分:1)

假设你要做的是要求用户输入两个hours:minutes数字,并计算他们之间的小时数+小时数,然后像现在一样使用日期时间,你会做类似的事情(简化) ):

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

或者,如果没有日期时间代码,我们可以这样做:

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

然而,如果有人在某一天下午6点开始并在第二天凌晨3点结束,那么这将失败,所以你可能想重新考虑你的逻辑