使用Python查找系统时间和互联网时间之间的偏移量

3

如何使用Python从各种互联网时间源中找到本地操作系统系统时间和互联网时间之间的时间偏移量?

2个回答

6

使用ntplib。以下是手册内容:

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

这是一个老问题,但负偏移或正偏移意味着什么?我不确定哪个是领先的,PC时间还是时间服务器时间? - wondim
@wondim positive = 远程NTP服务器领先。在答案示例中,我的本地时钟略微过快。 - phihag
谢谢!我的是-4,所以它向前走是很奇怪的。 - wondim

1

为了节省您的时间,这是我使用phihag的答案最终得出的代码。它将漂移每interval_sec秒打印到屏幕和日志文件中。
您需要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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接