Drill

ProblemsPython › dates

How many days in this month

easydatesPython

A date picker greys out the days that do not exist in the month being shown.

days_in_month(year: int, month: int) → int

Solve it in the editor →

Where you start

def days_in_month(year: int, month: int) -> int:
    

Worked examples

CallResult
days_in_month(2024, 2)29
days_in_month(2023, 2)28
days_in_month(1900, 2)28
days_in_month(2024, 4)30

Hint

A lookup table for the eleven easy months, and one branch for February.

Reference solution in Python
def days_in_month(year: int, month: int) -> int:
    if month < 1 or month > 12:
        return 0
    table = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    if month != 2:
        return table[month - 1]
    leap = year % 400 == 0 or (year % 4 == 0 and year % 100 != 0)
    return 29 if leap else 28

The same problem in another language

More dates problems in Python