Python NTP Library
ntplib is a Python module offering a simple interface to query Network Time Protocol (NTP) servers. It provides functionality to request time and status information from NTP servers and includes utility functions to translate NTP field values (like mode or leap indicator) into human-readable text. It is a pure Python library with no external dependencies beyond core modules, ensuring broad compatibility across various platforms. The latest release, 0.4.0, was on May 28, 2021, indicating a mature library with a moderate release cadence.
Warnings
- breaking A bug in `ntplib` version 0.3.3 could cause exceptions when attempting to translate the `stratum` field to text using utility functions. This issue was resolved in version 0.4.0.
- gotcha NTP requests require UDP port 123 to be open for both outbound requests and inbound responses. Firewall rules or network access control lists (ACLs) blocking this port will prevent `ntplib` from successfully communicating with NTP servers.
- gotcha The `NTPClient.request()` method is a blocking call. In applications requiring high concurrency or responsiveness, calling this method directly in the main thread can cause freezes or performance issues. Consider running NTP requests in a separate thread or using asynchronous execution.
- gotcha Users of PythonAnywhere's free tier may encounter `Errno 1: Operation not permitted` errors when attempting to use `ntplib`. This is due to platform-specific outbound network restrictions on non-whitelisted domains.
Install
-
pip install ntplib
Imports
- ntplib
import ntplib
- NTPClient
from ntplib import NTPClient
Quickstart
import ntplib
from time import ctime
def get_ntp_time(server='pool.ntp.org', version=3):
"""Queries an NTP server and prints selected response fields."""
try:
client = ntplib.NTPClient()
response = client.request(server, version=version)
print(f"NTP Server: {server}")
print(f"Offset: {response.offset:.4f} seconds")
print(f"Version: {response.version}")
print(f"NTP Time: {ctime(response.tx_time)}")
print(f"Leap Indicator: {ntplib.leap_to_text(response.leap)}")
print(f"Root Delay: {response.root_delay:.4f} seconds")
# ref_id_to_text may take stratum as a second argument in newer versions
print(f"Reference ID: {ntplib.ref_id_to_text(response.ref_id, response.stratum)}")
except ntplib.NTPException as e:
print(f"NTP request failed: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
# Use a common NTP pool server
get_ntp_time('pool.ntp.org')
# You can also try other servers like 'time.google.com' or 'ntp.org'
# get_ntp_time('time.google.com')