Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to print the days in a given month using Python?
To print the days in a given month using Python, we can use Pandas to work with date series and extract the number of days using the dt.daysinmonth attribute. This is particularly useful when working with date datasets and you need to know how many days are in specific months.
Solution
To solve this, we will follow the steps given below ?
Import pandas library
Create a date range using
pd.date_range()Convert to pandas Series
Use
Series.dt.daysinmonthto find the number of days
Example
Let us see the complete implementation to get a better understanding ?
import pandas as pd
# Create date range for February 2020
date = pd.date_range('2020-02-10', periods=1)
data = pd.Series(date)
print("Number of days in the month:")
print(data.dt.daysinmonth)
The output of the above code is ?
Number of days in the month: 0 29 dtype: int64
Working with Multiple Dates
You can also find days in multiple months at once ?
import pandas as pd
# Create date range spanning different months
dates = pd.date_range('2020-01-15', periods=4, freq='M')
data = pd.Series(dates)
print("Dates:")
print(data)
print("\nDays in each month:")
print(data.dt.daysinmonth)
The output of the above code is ?
Dates: 0 2020-01-31 1 2020-02-29 2 2020-03-31 3 2020-04-30 dtype: datetime64[ns] Days in each month: 0 31 1 29 2 31 3 30 dtype: int64
Alternative Approach Using Calendar Module
For simple date calculations, you can also use Python's built-in calendar module ?
import calendar
# Get number of days in February 2020
year = 2020
month = 2
days = calendar.monthrange(year, month)[1]
print(f"Days in {year}-{month:02d}: {days}")
# Check if it's a leap year
print(f"Is {year} a leap year? {calendar.isleap(year)}")
The output of the above code is ?
Days in 2020-02: 29 Is 2020 a leap year? True
Conclusion
Use pandas.Series.dt.daysinmonth when working with date series to get days in months. For simple calculations, Python's calendar.monthrange() provides a lightweight alternative. Both methods correctly handle leap years.
