简体   繁体   中英

Need to check current time from NTP server is within some time range in python

I need to check if current time from NTP server (using ntplib module) is within some required time range.

I have written the below code but I need some help to finish this task.

#!/usr/bin/python

import ntplib

from time import ctime

ntp_client = ntplib.NTPClient()
response = ntp_client.request('pool.ntp.org')

print (ctime(response.tx_time))

Output:

Fri Aug 16 13:26:16 2019

Now I need to check the ntp current time "13:26:16" is within the time range "09:30:00 - 15:30:00", so how can we check this in Python?

It must say current ntp time is/not in time range "09:30:00 - 15:30:00"

Convert the epoch timestamp to a suitable representation such as a Python datetime object and inspect the hours and minutes fields.

from time import gmtime
# ...
dt = time.gmtime(response.tx_time)
if (dt.tm_hour == 9 and dt.tm_min >= 30) or (
    10 <= dt.tm_hour <= 14) or (
        dt.tm_hour == 15 and dt.tm_min <= 30):
    print('yes indeed')
else:
    print('not')

Time zones are always tricky; the above gets you UTC (as vaguely implied by the name gmtime ). If you want to compare to the value in your local time zone, try time.localtime instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM