距离 HH:MM 还剩几秒
Seconds left to HH:MM
我需要检查 Python 中最接近的 HH:MM 时间还剩多少秒(24 小时格式)。例如,现在是 10:00 - 我需要在同一天检查 16:30。
如果它 18:00 我需要检查到 16:30 第二天结束的剩余秒数等等。
如果你的格式得到保证,你可以很容易地计算出一天中的秒数:
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
您可能想使用 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
从简单的步骤开始。编程通常是将这些任务分解成步骤。
获取当前时间。获取下一个 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
使用日期时间:
import datetime
func = lambda s: datetime.datetime.strptime(s, '%H:%M')
seconds = (func(s2)-func(s1)).seconds
即使在特殊的 'next day' 情况下,您总能得到想要的,例如下面的案例 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
我需要检查 Python 中最接近的 HH:MM 时间还剩多少秒(24 小时格式)。例如,现在是 10:00 - 我需要在同一天检查 16:30。 如果它 18:00 我需要检查到 16:30 第二天结束的剩余秒数等等。
如果你的格式得到保证,你可以很容易地计算出一天中的秒数:
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
您可能想使用 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
从简单的步骤开始。编程通常是将这些任务分解成步骤。
获取当前时间。获取下一个 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
使用日期时间:
import datetime
func = lambda s: datetime.datetime.strptime(s, '%H:%M')
seconds = (func(s2)-func(s1)).seconds
即使在特殊的 'next day' 情况下,您总能得到想要的,例如下面的案例 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