Easy way to get the correct time in python

I'm dealing with a standalone sensor device that runs Linux 2.6.33, Python 2.6.5, and unfortunately lacks a real-time clock but does have networking capabilities. Additionally, the device uses BusyBox so it has a minimalized set of tool capabilities.

I created the script below that executes after the network is running to correct the system time. My solution might not exactly address the original question (sounds like Noah is a user and not an admin on the system), but this question is what comes when searching for sync'ing system clock using Python via NTP. I figure it might help others that land here.

Before you use the script, you'll need to install ntplib. The download link and installation instructions are here: https://pypi.python.org/pypi/ntplib/.

Copy the the contents of the code below to a file (I named mine "synctime.py"). Then, after the network is running, execute the script (e.g. "python synctime.py"). You will need to do this using elevated (root) privileges for this to work properly.

import time
import os

try:
    import ntplib
    client = ntplib.NTPClient()
    response = client.request('pool.ntp.org')
    os.system('date ' + time.strftime('%m%d%H%M%Y.%S',time.localtime(response.tx_time)))
except:
    print('Could not sync with time server.')

print('Done.')

Sounds like you should look into using something like NTP to keep the machines' time in sync with one another (and preferably, a global standard time source).


Try ntplib for python. I've played around with it a bit and it seems pretty stable.

https://pypi.python.org/pypi/ntplib/