machine.RTC().datetime() gives incorrect hours, minutes, and day of the week

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
botan
Posts: 1
Joined: Fri Apr 15, 2022 1:43 pm

Re: machine.RTC().datetime() gives incorrect hours, minutes, and day of the week

Post by botan » Fri Apr 15, 2022 1:59 pm

I just stumbled upon this topic during my search for clarification of the example for the Raspberry Pico https://docs.micropython.org/en/latest/ ... -clock-rtc. A brief look into the code of the RP2 port https://github.com/micropython/micropyt ... hine_rtc.c revealed the following structure:

Code: Select all

 mp_obj_t tuple[8] = {
            mp_obj_new_int(t.year),
            mp_obj_new_int(t.month),
            mp_obj_new_int(t.day),
            mp_obj_new_int(t.dotw),
            mp_obj_new_int(t.hour),
            mp_obj_new_int(t.min),
            mp_obj_new_int(t.sec),
            mp_obj_new_int(0)
        };
So in m case the correct format was: year, month, day, day-of-the-week (Mon = 0 ... Sun = 6), hour (0..23), minute, second, 0

I hope that helps others who search for the same problem.

And here is how a format conversion works:

Micropython (Epoch/Unix time based on the year 2000)

Code: Select all

>>> t_rtc = rtc.datetime()
>>> t_rtc
(2022, 10, 15, 5, 16, 29, 37, 606547)
>>> t_mktime = (t_rtc[0], t_rtc[1], t_rtc[2], t_rtc[4], t_rtc[5], t_rtc[6], t_rtc[7], t_rtc[3])
>>> t_2000 = time.mktime(t_rtc)
>>> t_2000
719126189
>>> t_1970 = t_2000 + 946684800 
>>> t_1970
1665810989
Python on PC (Epoch/Unix time based on the year 1970)

Code: Select all

>>> time.gmtime(1665810989)
time.struct_time(tm_year=2022, tm_mon=10, tm_mday=15, tm_hour=5, tm_min=16, tm_sec=29, tm_wday=5, tm_yday=288, tm_isdst=0)

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: machine.RTC().datetime() gives incorrect hours, minutes, and day of the week

Post by Roberthh » Sat Oct 15, 2022 3:56 pm

Thanks for the hint. Something is wrong. Either the argument order or the comment in the example. Interestingly, when we read that as the time being set to 12:48:00, the day-of-week number is 2, which is right.
The epoch is defined per port, depending on theRTC hardware. So with other ports it could be 1970.

Post Reply