micropythonraspberry-pi-picoreal-time-clock

How to check the last day of the month in MicroPython and/or RTC DS1307?


I have a Raspberry Pi Pico with MicroPython and a DS1307 clock connected to it. How can I check what is the last day of the month for a given year and month? I don't care about using RTC if it can be checked in MicroPython itself. For example, for January 2023 it is 31. For February 2023 it is 28. For March 2023 it is 31 and so on.

I searched the internet but couldn't find any answer.


Solution

  • I think this doesn't need a calculation/formula, since it is fixed:

    J: 31

    F: 28

    M: 31

    A: 30

    M: 31

    J: 30

    J: 31

    A: 31

    S: 30

    O: 31

    N: 30

    D: 31

    As for leap years:

    To be a leap year, the year number must be divisible by four – except for end-of-century years, which must be divisible by 400

    So just place the values in an array of size 12 (or a dictionary using month names for ease). Then for februaries, check if the year is divisible by 4. So if Y is the year, then:

    if (not (Y % 400)) or (not (Y % 4)):
        # leap year, ie feb is 29
    else:
        # not leap year, ie feb is 28