Python NTP Library

0.4.0 · active · verified Sun Apr 12

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

Install

Imports

Quickstart

This quickstart demonstrates how to create an `NTPClient` instance, send a request to a public NTP server, and access key fields from the `NTPResponse` object, including calculated offset and various NTP status indicators.

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

view raw JSON →