简体   繁体   English

使用 Python 查找系统时间和 Internet 时间之间的偏移量

[英]Find offset between system-time and Internet time using Python

How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?您如何使用 Python 从各种 Internet 时间源中找到本地操作系统系统时间和 Internet 时间之间的时间偏移?

Use ntplib .使用ntplib Right from the manual:直接从手册:

>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891

Just to save you some time.只是为了节省你一些时间。 Here's the code I ended up with using phihag's answer.这是我最终使用 phihag 答案的代码。 It prints the drift every interval_sec to screen and to a log file.它每隔interval_sec将漂移打印到屏幕和日志文件中。
You'll need to easy_install ntplib for it to work.您需要easy_install ntplib才能正常工作。

import logging
logging.basicConfig(filename='time_shift.txt',level=logging.DEBUG)

import ntplib
import time
import datetime
c = ntplib.NTPClient()

interval_sec = 60
while True:
    try:
        response = c.request('europe.pool.ntp.org', version=3)
        txt = '%s     %.3f' % (datetime.datetime.now().isoformat(), response.offset)
        print txt
        logging.info(txt)
    except:
        pass
    time.sleep(interval_sec)

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

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