2017-08-25 Python2> datetime> Wait until start hour, minute, second

Operating environment


Raspberry Pi 2 Model B (Below RPi)
Raspbian Jessie
Python 2.7.9

Waiting until the start time is required to have RPi take charge of the automatic logging function.

I implemented it as follows.

test_wait_170825.py


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import serial
import datetime

# SET start time
start_time = datetime.time(13,45,0)

start_str = start_time.strftime("%H:%M:%S")

while True:
    now_time = datetime.datetime.now()
    if start_str == now_time.strftime("%H:%M:%S"):
        break
    time.sleep(0.1)  # [sec]

print('hello')
print(datetime.datetime.now())

run


$ python test_wait_170825.py 
hello
2017-08-25 13:45:00.074149

The polling interval for time.sleep () could be a little longer (like 0.3).

There is a way to use crontab for this kind of processing, but I implemented it in Python because I want to manage it collectively with Python code.

For import

util_wait_170825.py


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import datetime

def wait_until(HH, MM, SS):
    start_time = datetime.time(HH, MM, SS)
    start_str = start_time.strftime("%H:%M:%S")

    while True:
        now_time = datetime.datetime.now()
        if start_str == now_time.strftime("%H:%M:%S"):
            break
        time.sleep(0.1)  # [sec]

if __name__ == '__main__':
    print('start waiting')
    wait_until(13, 58, 30)  # HH, MM, SS

    print('hello')
    print(datetime.datetime.now())

For import> v0.2

I used the implementation method of @shiracamus. Thank you for the information.

util_wait_170825.py


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import datetime


def wait_until(HH, MM, SS):
    now = datetime.datetime.now()
    start = datetime.datetime(now.year, now.month, now.day, HH, MM, SS)
    wait_sec = (start - now).total_seconds()
    if wait_sec < 0:
        wait_sec += datetime.timedelta(days=1).total_seconds()
    time.sleep(wait_sec)


if __name__ == '__main__':
    print('start waiting')
    wait_until(14, 33, 30)  # HH, MM, SS

    print('hello')
    print(datetime.datetime.now())

Recommended Posts

2017-08-25 Python2> datetime> Wait until start hour, minute, second
Start python
Python> datetime> runtime arguments> start processing immediately
Start using Python
Python quick start
[Python] Start studying