我想找到两次之间的区别,如(05:33,16:01)。所以我知道我需要编写一个可以做到这一点的脚本,我可以用这些def来做到这一点:
def diff_minutes(start_time, end_time):
"""returns the difference of two inputs
number, number -> number"""
return int(start_time - end_time)
def hours_and_minutes_str(hours, minutes):
"""returns a string that represents the time span, including units
number, number -> str"""
print (hours, 'hours' , minutes , "minutes")
def hours_and_minutes_to_minutes(hours, minutes):
"""returns the total minutes of the input
number, number -> number"""
return (hours * 60 + minutes)
def minutes_to_hours_and_minutes(minutes):
"""returns two numbers given just a number of minutes
number, number -> number"""
return (int(minutes/60), minutes%60)
def extract_hours(tm:'hours:minutes'):
"""returns an integer representing the number of hours
number, number -> number"""
return int(tm.split(':')[0])
def extract_minutes(tm:'hours:minutes'):
"""returns an integer representing the number of minutes
number, number -> number"""
return int(tm.split(':')[1])
感谢任何帮助。
答案 0 :(得分:3)
如果你只有几小时和几分钟,你可以使用timedelta
,这非常简单:
>>> from datetime import timedelta
>>> t1 = timedelta(hours=5, minutes=33)
>>> t2 = timedelta(hours=16, minutes=1)
>>> print((t2 - t1).total_seconds())
37680.0
>>> print (t2 - t1)
10:28:00
我没有您正在使用的实际输入,但似乎您知道如何将字符串映射到创建参数:)
通常,您可以使用'05'33'
和split
映射int
等字符串:
>>> hours, minutes = map(int, '05:33'.split(':'))
>>> hours
5
>>> minutes
33
答案 1 :(得分:2)
是的,绝对datetime就是你需要的。具体来说,是strptime
函数,它将字符串解析为时间对象。
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
这会得到一个timedelta
对象,其中包含两次之间的差异。你可以做任何你想做的事,例如将其转换为秒或将其添加到另一个datetime
。
答案 2 :(得分:0)
我强烈建议您使用标准Python库。请参阅Python reference。
import datetime
time1 = '05:33'
time2 = '16:01'
format = '%H:%M'
datetime1 = datetime.datetime.strptime(time1, format)
datetime2 = datetime.datetime.strptime(time2, format)
minutes = (datetime2 - datetime1).seconds / 60