简体   繁体   English

需要检查来自NTP服务器的当前时间是否在python中的某个时间范围内

[英]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. 我需要检查来自NTP服务器的当前时间(使用ntplib模块)是否在某些所需的时间范围内。

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? 现在,我需要检查ntp当前时间“ 13:26:16”是否在时间范围“ 09:30:00-15:30:00”内,那么我们如何在Python中进行检查?

It must say current ntp time is/not in time range "09:30:00 - 15:30:00" 必须指出当前ntp时间在/不在时间范围“ 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. 将纪元时间戳转换为合适的表示形式,例如Python datetime对象,并检查小时和分钟字段。

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 ). 上面的代码使您可以使用UTC(如gmtime隐含地暗示)。 If you want to compare to the value in your local time zone, try time.localtime instead. 如果要与本地时区中的值进行比较,请尝试使用time.localtime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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