Get the last day of the month
⚡TLDR
In a hurry and want to know the last day of any month? Here's your quick answer:
This code uses monthrange
from Python's built-in calendar
module, then constructs the date. Pretty neat, huh?
Moving beyond the basics - Diving deeper
Congratulations, you made it past the fast answer. Let's dive deeper to account for alternative methods and potential edge cases.
More ways to find the Last Jedi ... I mean, day
Finagling with datetime
and dateutil
: Here's how:
Taming the Pandas for time series: Your data science woes, answered:
Keeping an eye out for those pesky edge cases
- Need a bit of a leap?: Our friend
calendar.monthrange()
has your back. It has been handling leap years way before they were cool. - Oh dear, December!: Watch out for year-end festivities. Revisit your roll over codes to ensure January doesn't feel left out.
- Beware of Time thieves: While dealing with time zones and daylight saving time changes, protect your dates. No one likes their days stolen!
Picture perfect with visualisation
A picture is worth a thousand lines of code...
Here's our calendar toolbox:
And the puzzle pieces of each month's last day. Yeah, we're missing a few:
Wait! calendar.monthrange(year, month)
fits the missing piece.
And the last piece fits! February's last day:
Your puzzle is now complete!
Linked
Was this article helpful?