将时间转换为浮点数 [英] Converting time to a float
本文介绍了将时间转换为浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我编写了一个程序来计算工作时间,但最后,它返回的值是时间。
I wrote a program to compute the hours I've worked but at the end, it returns the value as a time.
例如:我从11岁开始工作: 45至4:30。
我的程序返回4:45我希望它返回4.75。
EX: I worked from 11:45 to 4:30. My program returns 4:45 I would like it to return 4.75.
我如何转换它?
我正在使用以下代码:
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)
推荐答案
如果您使用日期时间,则小时和分钟方法应该可以为您提供所需的信息
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
这篇关于将时间转换为浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文