
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Number of days in a month in Python
Suppose we have one year Y and a month M, we have to return the number of days of that month for the given year. So if the Y = 1992 and M = 7, then the result will be 31, if the year is 2020, and M = 2, then the result is 29.
To solve this, we will follow these steps −
- if m = 2, then
- if y is a leap year, return 29, otherwise 28
- make an array with elements [1,3,5,7,8,10,12]
- if m is in the list, then return 31, otherwise, return 30.
Example(Python)
Let us see the following implementation to get a better understanding −
class Solution(object): def numberOfDays(self, y, m): leap = 0 if y% 400 == 0: leap = 1 elif y % 100 == 0: leap = 0 elif y% 4 == 0: leap = 1 if m==2: return 28 + leap list = [1,3,5,7,8,10,12] if m in list: return 31 return 30 ob1 = Solution() print(ob1.numberOfDays(2020, 2))
Input
2020 2
Output
29
- Related Articles
- C# Program to display the number of days in a month
- How to find out number of days in a month in MySQL?
- How to calculate number of days in a month or a year in Excel?
- How to get a number of days in a specified month using JavaScript?
- Python Pandas - Get the total number of days of the month that the Period falls in
- How to find the number of days in a month of a particular year in Java?
- How to print the days in a given month using Python?
- How to calculate the number of working days left in the current month in Excel?
- How to calculate days left in a month or year in Excel?
- Getting month name instead of numeric month number in report in SAP
- Get Month Name from Month number in MySQL?
- Python Pandas - Get the number of days from TimeDelta
- Program to find minimum number of days to eat N oranges in Python
- Getting calendar for a month in Python
- Output only the name of the month instead of the month number in MySQL

Advertisements