0

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.

Łukasz
  • 3
  • 3

2 Answers2

0

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
mo FEAR
  • 552
  • 4
  • 8
0

I found on Wikipedia:

  • is divisible by 4 and not divisible by 100 or
  • is divisible by 400

So I guess it'll be like this:

def month_length(year, month):
    length_of_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if (not (year % 400)) or (not (year % 4) and year % 100 is not 0) and month == 2:
        month_length = 29
    else:
        month_length = length_of_months[month-1]
    return month_length

Thank you!

Łukasz
  • 3
  • 3