Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ntp client in python

Tags:

python

I've written a ntp client in python to query a time server and display the time and the program executes but does not give me any results. I'm using python's 2.7.3 integrated development environment and my OS is Windows 7. Here is the code:

# File: Ntpclient.py
from socket import AF_INET, SOCK_DGRAM
import sys
import socket
import struct, time

# # Set the socket parameters 

host = "pool.ntp.org"
port = 123
buf = 1024
address = (host,port)
msg = 'time'


# reference time (in seconds since 1900-01-01 00:00:00)
TIME1970 = 2208988800L # 1970-01-01 00:00:00

# connect to server
client = socket.socket( AF_INET, SOCK_DGRAM)
client.sendto(msg, address)
msg, address = client.recvfrom( buf )

t = struct.unpack( "!12I", data )[10]
t -= TIME1970
print "\tTime=%s" % time.ctime(t)
like image 629
Howard Hugh Avatar asked Sep 30 '12 19:09

Howard Hugh


People also ask

What is NTP in Python?

Advertisements. The most widely used protocol for synchronizing time and which has been widely accepted as a practice is done through Network Time Protocol (NTP).

What is NTP client Linux?

The NTP client enables the appliance or virtual machine to synchronize its internal clock with an NTP server on your network or on the internet. You can also configure the NTP client through the UI, see Performing time synchronization.


1 Answers

Use ntplib:

The following should work on both Python 2 and 3:

import ntplib
from time import ctime
c = ntplib.NTPClient()
response = c.request('pool.ntp.org')
print(ctime(response.tx_time))

Output:

Fri Jul 28 01:30:53 2017
like image 172
Anuj Gupta Avatar answered Sep 30 '22 20:09

Anuj Gupta