'Can the tuples be changed in rtc.datetime()?

import network, ntptime, time
from machine import RTC

# dictionary that maps string date names to indexes in the RTC's 
datetime tuple
DATETIME_ELEMENTS = {
    "year": 0,
    "month": 1,
    "day": 2,
    "day_of_week": 3,
    "hour": 4,
    "minute": 5,
    "second": 6,
    "millisecond": 7
}

def connect_to_wifi(wlan, ssid, password):
    if not wlan.isconnected():
        print("Connecting to network...")
        wlan.connect(ssid, password)
        while not wlan.isconnected():
            pass

# set an element of the RTC's datetime to a different value
def set_datetime_element(rtc, datetime_element, value):
    date = list(rtc.datetime())
    date[DATETIME_ELEMENTS[datetime_element]] = value
    rtc.datetime(date)


wlan = network.WLAN(network.STA_IF)
wlan.active(True)

connect_to_wifi(wlan, "SSID", "Password")

rtc = RTC()
ntptime.settime()

set_datetime_element(rtc, "hour", 8) # I call this to change the hour to 8am for me


print(rtc.datetime()) # print the updated RTC time

Prints results:

(2022, 4, 28, 3, 18, 50, 27, 0)
(2022, 4, 28, 3, 8, 50, 27, 0)

I'm trying to get:

(2022, 4, 28, 8, 50, 27)

I don't want the day or microseconds. Any suggestions?



Solution 1:[1]

If you only want to print a subset of the fields in the tuple, you can use Python's slicing operating (see e.g. the examples here to select only those fields:

>>> now=(2022, 4, 28, 3, 18, 50, 27, 0)
>>> print(now)
(2022, 4, 28, 3, 18, 50, 27, 0)
>>> print(now[:3] + now[5:7])
(2022, 4, 28, 50, 27)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 larsks