开发者

python datetime.time operation

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

I need the minute interval between between two times. For instance a non working one:

def minute_interval(start,end):
     return end - start

minute_interval(t1,t2) #should give 63 mins.

Also if the end time is smaller than start, it should do the calculation by understaing the end is from the next days time. ie:

minute_int开发者_JAVA百科erval(t3,t4) #should give 75 mins.

How can this be achieved ? I need to rewrite the minute_interval function for this aim.


Assuming time are in same timezone and no 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)

output:

63
75

otherwise you are better of using datetime.datetime, which supports subtraction and gives datetime.timedelta, for timezone you can use pytz library.


How's this?

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜