prashantb j
prashantb j

Reputation: 423

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"

Upvotes: 0

Views: 1186

Answers (1)

tripleee
tripleee

Reputation: 189809

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.

Upvotes: 1

Related Questions