# Recommended way for a python script to check NTP update status, and initiate an update if necessary?

I am writing a data logging python script and I would like it to find out if the system clock has been synchronized via NTP recently, and if not, to attempt to cause it to happen before proceeding.

Starting from this answer, I've found that for the status

os.system('sudo service ntp status')


will display the results on the console, but I don't know how I can get the python script to see if ntp is active or not, since this call returns only 0.

I could always just force a reset even if not needed using

os.system('sudo service ntp stop')
os.system('sudo ntpd -gq')
os.system('sudo service ntp start')


but it seems like a bad idea to do that if it wasn't necessary.

edit: using Raspbian GNU/Linux 8 (jessie)

Question: How can I test the status and then conditionally force a synchronization only if needed?

This answer suggests the package ntplib https://pypi.python.org/pypi/ntplib/ but I'm not sure if this is advisable or not, so I thought I'd ask before installing and running it, and I'd still have to guess the status by comparing the results to the system clock and deciding if the agreement were good enough or not. I'd still like to know if ntp is active and that it believes the synchronization is close.

• You don't say what OS, but Stretch doesn't use ntpd – Milliways Mar 11 '18 at 22:57
• "Raspbian 4.4.21-v7+" is meaningless - it is basically the kernel version /etc/os-release will show release, but you should tag your question with OS – Milliways Mar 11 '18 at 23:18
• @Milliways thanks, cat returns Raspbian GNU/Linux 8 (jessie) – uhoh Mar 11 '18 at 23:56
• @Fabian loaded and disabled. Once enabled, does this only induce synchronization, or can I use it to check the status by calling within a python script using os.system()? – uhoh Mar 12 '18 at 0:01
• lsb_release -irc works nicely as well. – uhoh Mar 12 '18 at 0:19