RobouteGuiliman
RobouteGuiliman

Reputation: 201

How to get time from an NTP server?

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))

Upvotes: 11

Views: 41978

Answers (5)

Ahmad Asmndr
Ahmad Asmndr

Reputation: 355

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())

Upvotes: 12

hum3
hum3

Reputation: 1711

This is basically Ahmads answer but working for me on Python 3. I am currently keen on Arrow as simplifying times and then you get:

import arrow
import socket
import struct
import sys

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 arrow.get(t)

print(RequestTimefromNtp())

Upvotes: 2

windstorm
windstorm

Reputation: 385

The timestamps returned as call to the NTP server returns time in seconds. ctime() provides datetime format based on local machine's timezone settings by default. Thus, for uk timezone you need to convert tx_time using that timezone. Python's in-built datetime module contains function for this purpose

import ntplib
from datetime import datetime, timezone
c = ntplib.NTPClient()
# Provide the respective ntp server ip in below function
response = c.request('uk.pool.ntp.org', version=3)
response.offset
print (datetime.fromtimestamp(response.tx_time, timezone.utc))

UTC timezone used here. For working with different timezones you can use pytz library

Upvotes: 10

T.Sh
T.Sh

Reputation: 390

The following function is working well using python 3:

def GetNTPDateTime(server):
    try:
        ntpDate = None
        client = ntplib.NTPClient()
        response = client.request(server, version=3)
        ntpDate = ctime(response.tx_time)
        print (ntpDate)
    except Exception as e:
        print (e)
    return datetime.datetime.strptime(ntpDate, "%a %b %d %H:%M:%S %Y")

Upvotes: 1

Related Questions