几秒钟留给HH:MM

时间:2015-06-22 08:01:55

标签: python python-2.7 python-datetime

我需要检查lef到leff的最近HH:MM时间的秒数(24小时格式)。例如,现在是10:00 - 我需要在当天16:30检查。 如果它的18:00我需要检查第二天16:30结束的那么结束。

4 个答案:

答案 0 :(得分:1)

您可能想要使用datetime模块,timeldelta是您的朋友:

import datetime

def cal_delta_to(hour, minute):
    now = datetime.datetime.now()
    target = datetime.datetime(*now.timetuple()[0:3], hour=16, minute=30)

    if target < now:  # if the target is before now, add one day
        target += datetime.timedelta(days=1)

    diff = now - target
    return diff.seconds

答案 1 :(得分:0)

如果确保了您的格式,您可以轻松计算当天的秒数:

def seconds_of_day(hhmm):
    return int(hhmm[:2])*3600 + int(hhmm[3:])*60

完成此操作后,比较很简单:

t1 = seconds_of_day('16:30')
t2 = seconds_of_day('10:00')
#t2 = seconds_of_day('18:01')
diff = 86400-t2+t1 if t1<t2 else t1-t2

答案 2 :(得分:0)

从简单的步骤开始。编程通常是将这些任务分解为步骤。

获取当前时间。下一个16:30。减去。

# use datetime
from datetime import datetime, timedelta

# get current time
curr = datetime.now()

# create object of nearest 16:30
nearest = datetime(curr.year, curr.month, curr.day, 16, 30)

# stupidly check if it's indeed the next nearest
if nearest < curr:
    nearest += timedelta(days=1)

# get diff in seconds
print (nearest - curr).seconds

答案 3 :(得分:-1)

使用 datetime

import datetime

func = lambda s: datetime.datetime.strptime(s, '%H:%M')
seconds = (func(s2)-func(s1)).seconds

即使在特殊的&#39;第二天案例中,您也可以随时获得所需内容,例如下面的案例1;

# case1: now is '09:30', check seconds left to the 09:29 next day
>>> (func('09:29')-func('09:30')).seconds
86340

# case2: now is '09:30', check 10:30 the same day
>>> (func('10:30')-func('09:30')).seconds
3600