How to get time from an NTP server?
Asked Answered
R

5

11

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))
Recuperative answered 8/4, 2016 at 12:58 Comment(0)
S
11

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())
Shirelyshirey answered 15/6, 2019 at 19:33 Comment(2)
To make it work for me this line had to be explicitly bytes: data = b'\x1b' + 47 * b'\0'Linsang
For the UK use addr='0.uk.pool.ntp.org'.Aniakudo
M
10

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

Mississippian answered 13/3, 2018 at 12:16 Comment(0)
L
2

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())
Linsang answered 8/9, 2020 at 18:53 Comment(0)
M
1

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")
Mcandrew answered 23/2, 2019 at 8:49 Comment(1)
requires the following imports: from time import * import ntplib import datetime also, the line "response.offset" does nothing also, to get the ntp unix time one only has to run: client = ntplib.NTPClient() response = client.request(server, version=3) (and only import ntplib)Dunfermline
A
-2

I used ntplib server and get date and change format in dd-mm-yyyy

Apologize answered 8/12, 2022 at 7:15 Comment(3)
Post the information in the link next to the link itselfDiver
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From ReviewBoney
And the link is to an image rather than text - forcing the user to use OCR or a bit of manual typing.Jacobite

© 2022 - 2024 — McMap. All rights reserved.