【发布时间】:2011-07-08 08:28:14
【问题描述】:
您如何使用 Python 从各种 Internet 时间源中找到本地操作系统系统时间和 Internet 时间之间的时间偏移?
【问题讨论】:
标签: python systemtime
您如何使用 Python 从各种 Internet 时间源中找到本地操作系统系统时间和 Internet 时间之间的时间偏移?
【问题讨论】:
标签: python systemtime
使用ntplib。直接来自手册:
>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891
【讨论】:
只是为了节省您一些时间。这是我最终使用 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)
【讨论】: