Today I tested the ntplib python package on Fedora 42 with the python 3.13.0 version.
This is the source code:
from ntplib import NTPClient
import socket
import os
import datetime
def sync_ntp_server(server_address='pool.ntp.org'):
try:
client = NTPClient()
response = client.request(server_address)
# Get the offset in seconds
offset = response.offset
# Calculate the drift rate (seconds per day)
drift_rate = offset * 86400 / response.tx_time
print(f"NTP synchronization successful. Offset: {offset:.2f} seconds")
print(f"Drift rate: {drift_rate:.2f} seconds per day")
# Apply the offset to the system clock
os.system(f"date -s '@{response.tx_time}'")
# Optionally, you can also apply the drift rate to the system clock
# However, this is generally not recommended as it can lead to further drift
# os.system(f"ntpdate -d {server_address}")
except Exception as e:
print(f"Error synchronizing NTP: {e}")
# Disable SELinux temporarily
os.system("setenforce 0")
# Sync with NTP server
sync_ntp_server()
# Print current system time after sync
current_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f"Current system time after sync: {current_time}")
The result is output is in the romanian language but this is not a problem for programmers:
[mythcat@fedora network_python_tools]$ pip install ntplib
Defaulting to user installation because normal site-packages is not writeable
Collecting ntplib
Downloading ntplib-0.4.0-py2.py3-none-any.whl.metadata (1.6 kB)
Downloading ntplib-0.4.0-py2.py3-none-any.whl (6.8 kB)
Installing collected packages: ntplib
Successfully installed ntplib-0.4.0
[mythcat@fedora network_python_tools]$ python ntplib_test_001.py
...
NTP synchronization successful. Offset: -5.25 seconds
Drift rate: -0.00 seconds per day
date: nu se poate stabili data: Operație nepermisă
vineri 25 octombrie 2024, 22:24:13 +0300
Current system time after sync: 2024-10-25 22:24:19