Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the Time and Date via Python/Linux

Tags:

python

linux

I am developing an inventory control system that will hopefully be deployed within several of our plants. I am going to be using a Linux SBC (Pi, Beaglebone......etc.) platform. I want my user interface to be non-Linux so that the end user does not need to know the Linux OS or how to navigate using the command line. My app will auto-launch at boot and provide the end user with all the necessary front end with a Python/Tkinter HMI. My prototype is based on the Raspberry Pi B. Because many of the installations may not have a network available I need a way to set the system time thru the user interface via python. I am using a Dallas 3231 RTC I2C chip on the GPIO pins with the i2C interface. Everything is worked out except there does not seem to be a simple way for Python to set the system time, write it to the RTC, and ignore the NPT sync if a network is available. This may be super simple, but I am stumped.

like image 1000
Scott Sutton Avatar asked Jun 03 '26 23:06

Scott Sutton


2 Answers

Someone might come up with something better, but here's how I've done it in the past.

import subprocess
import datetime

try:
    subprocess.check_call("ntpdate") #Non-zero exit code means it was unable to get network time
except subprocess.CalledProcessError:
    dt = getRTCTime() # Get time from RTC as a datetime object
    subprocess.call(['sudo', 'date', '-s', '{:}'.format(dt.strftime('%Y/%m/%d %H:%M:%S'))], shell=True) #Sets system time (Requires root, obviously)

#Rest of code
like image 80
user982835 Avatar answered Jun 06 '26 13:06

user982835


Had a similar situation with Raspberry Pi 4 where I wanted to update the system time based on some input.

import time

def update_time(unix_time_as_string):
    clk_id = time.CLOCK_REALTIME
    time.clock_settime(clk_id, float(unix_time_as_string))

In my example, unix_time_as_string comes from a web interface and is something like '1581084210.006'.

like image 42
Kim Avatar answered Jun 06 '26 12:06

Kim