t1 = datetime.time(12, 10, 0, tzinfo=GMT1()) # 12:10
t2 = datetime.time(13, 13, 0, tzinfo=GMT1()) #13:13
t3 = datetime.time(23, 55, 0, tzinfo=GMT1()) #23:55
t4 = datetime.time(01, 10, 0, tzinfo=GMT1()) #01:10
我需要两次之间的分钟间隔。例如,一个不工作的人:
def minute_interval(start,end):
return end - start
minute_interval(t1,t2) #should give 63 mins.
此外,如果结束时间小于开始时间,则应通过了解结束时间来自下一天的时间进行计算。即:
minute_interval(t3,t4) #should give 75 mins.
如何实现这一目标?我需要为这个目标重写minute_interval函数。
答案 0 :(得分:2)
假设时间在同一时区且没有DST
import datetime
def minute_interval(start, end):
reverse = False
if start > end:
start, end = end, start
reverse = True
delta = (end.hour - start.hour)*60 + end.minute - start.minute + (end.second - start.second)/60.0
if reverse:
delta = 24*60 - delta
return delta
t1 = datetime.time(12, 10, 0) # 12:10
t2 = datetime.time(13, 13, 0) #13:13
t3 = datetime.time(23, 55, 0) #23:55
t4 = end = datetime.time(01, 10, 0) #01:10
print minute_interval(t1, t2)
print minute_interval(t3, t4)
输出:
63
75
否则你最好使用datetime.datetime,它支持减法并给出datetime.timedelta,对于你可以使用pytz库的时区。
答案 1 :(得分:0)
>>> import datetime
>>> t1 = datetime.time(12, 10, 0)
>>> t2 = datetime.time(13, 13, 0)
>>> today = datetime.datetime.today()
>>> t1n = datetime.datetime.combine(today, t1)
>>> t2n = datetime.datetime.combine(today + datetime.timedelta(days=int(t2 < t1)), t2)
>>> d = t2n - t1n
>>> (d.days * 86400 + d.seconds) // 60
63
答案 2 :(得分:0)
这是怎么回事?
def minute_interval(start,end):
start_sec= (start.hour*60+start.minute)*60+start.second
end_sec= (end.hour*60+end.minute)*60+end.second
return (end_sec-start_sec)/60.0