LoginSignup
3
8

More than 3 years have passed since last update.

2017-08-25 Python2 > datetime > 開始時分秒まで待つ

Last updated at Posted at 2017-08-25
動作環境
Raspberry Pi 2 Model B (以下RPi)
Raspbian Jessie
Python 2.7.9

自動ロギング機能をRPiに担ってもらうため、開始時刻までの待ち処理が必要。

以下のように実装した。

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

time.sleep()のポーリング間隔はもう少し長くしてもいいだろう (0.3とか)。

こういう処理はcrontabを使う方法もあるが、Pythonコードでまとめて管理したい理由からPython実装した。

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())

import用 > v0.2

@shiracamus さんの実装方法を使わせていただきました。
情報感謝です。

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())

3
8
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
8