Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get time from an NTP server?

Tags:

python

ntp

I need to get the time for the UK from an NTP server. Found stuff online however any time I try out the code, I always get a return date time, the same as my computer. I changed the time on my computer to confirm this, and I always get that, so it's not coming from the NTP server.

import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('uk.pool.ntp.org', version=3)
response.offset
print (ctime(response.tx_time))
print (ntplib.ref_id_to_text(response.ref_id))

x = ntplib.NTPClient()
print ((x.request('ch.pool.ntp.org').tx_time))
like image 962
RobouteGuiliman Avatar asked Apr 08 '16 12:04

RobouteGuiliman


People also ask

Can the system clock get its date and time from a NTP server?

You can easily keep your system's date and time accurate by using network time protocol (NTP). Having an accurate clock on your server ensures that timestamps in emails sent from your machine are correct.

How can I query an NTP server under Linux?

An ntp server can be tested by asking it for the date using the ntpdate command. The parameter -q is for query only, don't set the clock. The command will return the exit code of 0 if successful. ntpdate ships with ntp package.

What is NTP timestamp?

State Variables and Formats NTP timestamps are represented as a 64-bit fixed-point number, in seconds relative to 0000 UT on 1 January 1900. The integer part is in the first 32 bits and the fraction part in the last 32 bits, as shown in the following diagram.


1 Answers

This will work (Python 3):

import socket
import struct
import sys
import time

def RequestTimefromNtp(addr='0.de.pool.ntp.org'):
    REF_TIME_1970 = 2208988800  # Reference time
    client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    data = b'\x1b' + 47 * b'\0'
    client.sendto(data, (addr, 123))
    data, address = client.recvfrom(1024)
    if data:
        t = struct.unpack('!12I', data)[10]
        t -= REF_TIME_1970
    return time.ctime(t), t

if __name__ == "__main__":
    print(RequestTimefromNtp())
like image 63
Ahmad Asmndr Avatar answered Oct 12 '22 02:10

Ahmad Asmndr