3

How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?

Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359

2 Answers2

6

Use ntplib. Right from the manual:

>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891
phihag
  • 278,196
  • 72
  • 453
  • 469
  • This is an old question but what does the negative or positive offset mean? I am not sure which one is ahead, the PC time or time server time? – wondim Oct 30 '20 at 21:55
  • @wondim positive = remote NTP server is ahead. In the example in the answer itself, my local clock was slightly too fast. – phihag Oct 31 '20 at 11:17
  • Thank you! Mine was -4 so it is strange how it goes that ahead. – wondim Oct 31 '20 at 14:50
1

Just to save you some time. Here's the code I ended up with using phihag's answer. It prints the drift every interval_sec to screen and to a log file.
You'll need to easy_install ntplib for it to work.

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)
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359