Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Last active December 3, 2025 00:33
Show Gist options
  • Select an option

  • Save stonehippo/2e0552fc40d2682d3e0de3aff592aa09 to your computer and use it in GitHub Desktop.

Select an option

Save stonehippo/2e0552fc40d2682d3e0de3aff592aa09 to your computer and use it in GitHub Desktop.
RTC setup in CircuitPython

Setting up an Adafruit hardware realtime clock module and rtc in Circuitpython

The rtc module in CircuitPython is a standardized interface for realtime clock (RTC) devices. While it is possible to use an RTC directly from the instance of an RTC hardware driver, wrapping it with rtc has a couple of advantages:

  • time.time() and time.localtime() are backed by rtc, all clock source will be synchronized
  • rtc correctly handled the tm_yday (yearday) parameter, which may not be done by the hardware driver libary

Of course, you may not care about either of these, in which case rtc might be overkill and leaving it out can save you a little RAM.

RTC hardware from Adafruit

Adafruit has several RTC dev boards you can choose from.

  • DS1307 - tried and true, but requires 5v, so you might want to consider on the other options
  • PCF8523 - similar to the DS1307, but works with 3v or 5v
  • DS3231 - more accurate than the other two modules

I have linked to the STEMMA QT versions of the PCF8523 and DS3231, but they're also available in some other form factors. See the Adafruit clocks category page for more options.

import board
import time
import rtc
try:
if board.STEMMA_I2C:
i2c = board.STEMMA_I2C()
else:
i2c = board.I2C()
except AttributeError:
import busio
i2c = busio.I2C(board.SCL, board.SDA)
# use one of the Adafruit RTC modules
# from adafruit_pcf8523.pcf8523 import PCF8523 as rtc_driver
# import adafruit_ds3231 import DS3231 as rtc_driver
from adafruit_ds1307 import DS1307 as rtc_driver
# assume that the hardware RTC has already been set to real time
rtc_dev = rtc_driver(i2c)
# set the `rtc' module, which will sync `time.localtime()`/`time.time()` as well
r = rtc.RTC()
r.datetime = time.struct_time(tuple(rtc_dev.datetime))
print(f"rtc: {r.datetime}\n-----\nrtc_dev: {rtc_dev.datetime}")
# result will be something like this (note that the `rtc` module correctl handle yearday
# rtc: struct_time(tm_year=2025, tm_mon=12, tm_mday=2, tm_hour=19, tm_min=17, tm_sec=42, tm_wday=1, tm_yday=336, tm_isdst=-1)
#-----
#rtc_dev: struct_time(tm_year=2025, tm_mon=12, tm_mday=2, tm_hour=19, tm_min=17, tm_sec=42, tm_wday=1, tm_yday=-1, tm_isdst=-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment