Update RTC time with python

129 Views Asked by At

I have a small computer running Armbian, similar to a RPi with an RTC connected to it on /dev/rtc1/.

my device is running mainly offline but connects to internet from time to time and I use this opportunity to sync my RTC.

I am using this code.

def update_clock_time():
try:
    import ntplib
    client = ntplib.NTPClient()
    response = client.request('pool.ntp.org')
    logger.info("updating system clock")
    os.system('date ' + time.strftime('%m%d%H%M%Y.%S',time.localtime(response.tx_time)))
    logger.info("updating hw clock0")
    os.system('hwclock -w -f /dev/rtc0')
    logger.info("updating hw clock1")
    os.system('hwclock -w -f /dev/rtc1')
except:
    print('Could not sync with time server.')

the idea is:

  1. I update the system time
  2. I update the RTC0 (no battery back up)
  3. I update RTC1 with battery back up

my script often bug when updating one of the RTC and doesn't get handled by the exception. I notice it often happens when the time on the RTC1 has never been sync first.

Does anyone knows how I could make my code more robust and/or handle the exception properly? What is the issue with my code?

0

There are 0 best solutions below