Seconds left to HH:MM

1k views Asked by At

I need to check how many seconds are lef to the nearest HH:MM time in Python (in 24 hour format). For example, now is 10:00 - I need to check 16:30 same day. If its 18:00 I need to check secods left to the 16:30 next day end so on.

4

There are 4 answers

0
Christian Geier On BEST ANSWER

You probably want to use the datetime module, timeldelta is your friend here:

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

If your format is ensured, you can easily calculate the seconds of the day:

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

Having done this the comparison is straightforward:

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

Start with simple steps. Programming is usually about breaking down tasks like these into steps.

Get current time. Get next 16:30. Subtract.

# 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
0
LittleQ On

Use datetime:

import datetime

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

You can always get what you want, even in the special 'next day' cases, like in case1 below;

# 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