【问题标题】:Find offset between system-time and Internet time using Python使用 Python 查找系统时间和 Internet 时间之间的偏移量
【发布时间】:2011-07-08 08:28:14
【问题描述】:

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

【问题讨论】:

    标签: python systemtime


    【解决方案1】:

    使用ntplib。直接来自手册:

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

    【讨论】:

    • 这是一个老问题,但负偏移或正偏移是什么意思?我不确定哪个是前面,PC时间还是时间服务器时间?
    • @wondim positive = 远程 NTP 服务器在前面。在答案本身的示例中,我的本地时钟有点太快了。
    • 谢谢!我的是-4,所以它是如何前进的很奇怪。
    【解决方案2】:

    只是为了节省您一些时间。这是我最终使用 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      • 2019-10-22
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多