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
muslpy 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.012s · 17.8MB
glibcpy 3.10–3.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.fixUpgrade 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.fixEnsure 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.fixFor 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.fixOn 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.
fixInstall 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.
fixVerify 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.
fixCheck 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).
fixThis 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.
fixTry 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.