1

I have a list which contains times like this ['13:45','12:30','11:40'] in string format. So, the script should pick the earliest time in the string format list and wait till that time occurs. The first part of code, picking the minimum can be done with min function. How to make it wait till that time?

And also, if the time mentioned the least one already completed(past) then it should pick the next lowest.

Stefan
  • 1,697
  • 15
  • 31
uday kiran
  • 63
  • 5

2 Answers2

0

There is a nuance in this problem: when the least time from the list is smaller than the current time. In this case, the most reasonable way is to sleep until the smallest time in the list tomorrow. E.g., let's consider current time 23:59 and tl = [00:10, 01:30], then the script should sleep until 00:10 (tomorrow).

Here is the solution:

import time
from datetime import datetime
from datetime import timedelta
from dateutil import parser

now = datetime.now()


def parse_times(tl):
    for t in tl:
        parsed_time = parser.parse(t)
        if parsed_time > now:
            yield parsed_time
        else:
            yield parsed_time + timedelta(days=1)


tl = ['13:45', '12:30', '11:40']

parsed_times = parse_times(tl)
next_time = min(parsed_times)
time.sleep((next_time - now).total_seconds())
user1635327
  • 1,469
  • 3
  • 11
-1

What about something like:

from time import sleep
from datetime import datetime

tl = ['13:45','12:30','11:40']

## remove times less or equal current time, then get minimum
t = min(el for el in tl if el > datetime.now().strftime('%H:%M'))

## sleep until we pass the minimum time
## we check this every second
while t > datetime.now().strftime('%H:%M'):
    sleep(1)

Stefan
  • 1,697
  • 15
  • 31
  • why don't you use `t=min(el for el in l if el > datetime.now().strftime('%H:%M'))`, calculate the seconds diff and wait that amount of seconds – rioV8 Aug 29 '20 at 06:22
  • @rioV8 ohh yes, you are right. I read the part with dropping past times later so I just added this line. I updated my answer. – Stefan Aug 29 '20 at 06:27
  • remove the `[]` you add a generator not a list – rioV8 Aug 29 '20 at 06:29
  • @rioV8 Why? What's the problem with the `[]`? Both return the correct minimum. – Stefan Aug 29 '20 at 06:32
  • there is no need to fist convert it to a list if you don't need the list, the list could be very large – rioV8 Aug 29 '20 at 06:45
  • @rioV8 Oh I see. I did the update. – Stefan Aug 29 '20 at 06:48
  • Unnecessary condition check after each second, you could simply calculate the seconds left to the next closest date, and sleep that amount of seconds. – nagyl Aug 29 '20 at 06:54
  • sleep((min(times) - dt.datetime.now()).total_seconds()) is giving negative value.ValueError: sleep length must be non-negative – uday kiran Aug 29 '20 at 08:29