How to Get First and Last Day of Month in Python
Use Python's
datetime module to get the first day by setting the day to 1, and use the calendar.monthrange() function to find the last day of the month. Combine these to get both dates easily.Syntax
To get the first day of a month, create a datetime.date object with the year, month, and day set to 1.
To get the last day, use calendar.monthrange(year, month) which returns a tuple where the second value is the number of days in that month.
python
import datetime import calendar year = 2024 month = 6 first_day = datetime.date(year, month, 1) last_day = datetime.date(year, month, calendar.monthrange(year, month)[1])
Example
This example shows how to print the first and last day of June 2024.
python
import datetime import calendar year = 2024 month = 6 first_day = datetime.date(year, month, 1) last_day = datetime.date(year, month, calendar.monthrange(year, month)[1]) print("First day:", first_day) print("Last day:", last_day)
Output
First day: 2024-06-01
Last day: 2024-06-30
Common Pitfalls
- Trying to get the last day by adding days manually can cause errors because months have different lengths.
- Using
datetime.datetime.now()without extracting year and month can lead to wrong results if you want a specific month. - Not importing the
calendarmodule will cause errors when callingmonthrange().
python
import datetime # Wrong: Adding 30 days always (incorrect for months with 28, 29, or 31 days) start_date = datetime.date(2024, 2, 1) wrong_last_day = start_date + datetime.timedelta(days=30) # Right: Using calendar.monthrange import calendar last_day = datetime.date(2024, 2, calendar.monthrange(2024, 2)[1]) print("Wrong last day:", wrong_last_day) print("Correct last day:", last_day)
Output
Wrong last day: 2024-03-02
Correct last day: 2024-02-29
Quick Reference
Summary tips to get first and last day of any month:
- First day:
datetime.date(year, month, 1) - Last day:
datetime.date(year, month, calendar.monthrange(year, month)[1]) - Always import
calendarformonthrange()
Key Takeaways
Use datetime.date(year, month, 1) to get the first day of the month.
Use calendar.monthrange(year, month)[1] to find the last day number of the month.
Avoid manually adding days to find month ends because months vary in length.
Always import the calendar module when using monthrange.
This method works for any year and month, including leap years.