How to get the number of days in a given month of a given year with Python

1 Answer

0 votes
def is_leap_year(year):
    return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

def days_in_month(year, month):
    days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    
    if month == 2 and is_leap_year(year):
        return 29
    
    return days[month - 1]



year = 2024
month = 2
    
print(f"Days in month: {days_in_month(year, month)}")
print(f"Days in month: {days_in_month(2025, 1)}")
print(f"Days in month: {days_in_month(2025, 2)}")
print(f"Days in month: {days_in_month(2025, 4)}")
 
 
 
'''
run:

Days in month: 29
Days in month: 31
Days in month: 28
Days in month: 30
 
'''

 



answered Feb 19, 2025 by avibootz
...