2
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.

此外,如果结束时间小于开始时间,则应该通过了解结束时间是从第二天的时间来进行计算。IE:

minute_interval(t3,t4) #should give 75 mins.

如何实现?为此,我需要重写 minute_interval 函数。

4

3 回答 3

3

假设时间在同一时区且没有 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 库。

于 2010-03-04T10:57:48.183 回答
1

这个怎么样?

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
于 2010-03-04T10:57:41.460 回答
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
于 2010-03-04T10:50:30.163 回答