Registry / http-networking / ntplib

ntplib

JSON →
library0.4.0pypypi✓ verified 22d ago

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.

pip install ntplib
INSTALL
IMPORT
SIG · NTPLIB
N
ntplib
http-networkingpythonv0.4.0
Install
1.6s avg
Import
11ms
Disk
16MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.012s · 17.8MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 1.6s · import 0.010s · 18MB
16MB installed
● package 16MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ntplib
import ntplib
Imports the entire ntplib module.
NTPClient
from ntplib import NTPClient
Imports the NTPClient class directly for common usage.

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')
Debug
Known issues
breakingA 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.
fix
Upgrade to `ntplib` version 0.4.0 or higher. If unable to upgrade, avoid `ntplib.stratum_to_text()` or handle potential `NTPException` errors.
affects: <=0.3.3
gotchaNTP 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.
fix
Ensure that UDP port 123 is open in any local or network firewalls, and that no ACLs are blocking NTP traffic.
affects: All versions
gotchaThe `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.
fix
For non-blocking operations, execute `NTPClient.request()` in a dedicated thread (e.g., using `threading` or `concurrent.futures`) or integrate with an asynchronous framework (e.g., `asyncio`) by wrapping the blocking call, though `ntplib` itself does not offer native async support.
affects: All versions
gotchaUsers 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.
fix
On PythonAnywhere, use a paid account which offers broader network access, or explore alternative methods for time synchronization if `ntplib` is used solely for timestamping (e.g., `datetime.now()` for local time or a whitelisted API for external time if available).
affects: All versions on restricted platforms
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'ntplib'
The 'ntplib' library is not installed in your Python environment.
fix
Install the library using pip: `pip install ntplib`
socket.gaierror: [Errno -2] Name or service not known
The NTP server hostname provided is incorrect, cannot be resolved by DNS, or there is a network configuration issue preventing name resolution.
fix
Verify the NTP server hostname is correct and that your system has proper DNS configuration and network connectivity. Try using a well-known server like 'pool.ntp.org' or its IP address.
OSError: [Errno 101] Network is unreachable
Your system cannot establish a network connection to the specified NTP server, often due to firewall rules, incorrect routing, or a general lack of internet connectivity.
fix
Check your network connection, firewall settings (ensure UDP port 123 is open), and routing. Confirm that the NTP server is reachable from your system.
OSError: [Errno 1] Operation not permitted
The Python script is attempting a network operation (like opening a raw socket) that is restricted by the operating system or the execution environment (e.g., in some sandboxed hosting services).
fix
This often requires changing the execution environment or platform. If on a restricted hosting service, you might need to use a different service or a workaround that doesn't involve raw socket access, if available (though `ntplib` inherently uses sockets). Ensure the user running the script has necessary network permissions.
NTPException: Invalid NTP packet
The response received from the NTP server was malformed or did not conform to the expected NTP packet format, possibly indicating a problem with the server or network corruption.
fix
Try querying a different, reliable NTP server (e.g., 'pool.ntp.org'). If the issue persists across multiple servers, inspect network conditions for potential interference or check for a newer version of the `ntplib` library.
Upgrade
Version history
0.4.0latest on PyPI · released May 28, 2021
Audit
Dependencies

No dependency data recorded yet.

Agent activity
16 hits · last 30 days
node
12
OpenAI (training)
2
Resources