您如何使用 Python 从各种 Internet 时间源中找到本地操作系统系统时间和 Internet 时间之间的时间偏移?
问问题
2067 次
2 回答
6
使用ntplib。直接从手册:
>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891
于 2011-07-08T08:32:39.167 回答
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)
于 2011-07-26T22:09:33.160 回答