使用Python找到系统时间与网络时间之间的偏差

3 投票
2 回答
2491 浏览
提问于 2025-04-16 21:05

你怎么用Python找出本地操作系统时间和来自不同互联网时间源的互联网时间之间的时间差呢?

2 个回答

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)
6

使用ntplib库。直接从手册上来看:

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

撰写回答