Explain Codes LogoExplain Codes Logo

Get the last day of the month

python
datetime
pandas
dateutil
Alex KataevbyAlex Kataev·Nov 3, 2024
TLDR

In a hurry and want to know the last day of any month? Here's your quick answer:

from calendar import monthrange from datetime import date year, month = 2023, 2 # Insert your desired year, month. Cats don't care but Python does. last_day = monthrange(year, month)[1] # Because indexing starts at 0, not on the calendar though. last_date = date(year, month, last_day) # Now we're talking - an actual date! print(last_date) # Voila! Your answer served faster than instant noodles.

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:

from datetime import datetime from dateutil.relativedelta import relativedelta # Yoda says, "A leap year, it can be." year, month = 2023, 2 last_date = datetime(year, month, 1) + relativedelta(months=1, days=-1) # Yeah, we've stolen a day from the next month. So what? print(last_date.date())

Taming the Pandas for time series: Your data science woes, answered:

import pandas as pd year, month = 2023, 2 # Time-travel anyone? last_date = pd.Timestamp(f'{year}-{month}-01') + pd.offsets.MonthEnd() # Offsets so powerful, it's scary! print(last_date.date())

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.
# Meet Mr. December, he has a tendency to roll over to next year. year, month = 2023, 12
  • 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:

📆: [January, February, March, ..., December]

And the puzzle pieces of each month's last day. Yeah, we're missing a few:

🧩: [31, ❓, 31, ..., 31]

Wait! calendar.monthrange(year, month) fits the missing piece.

import calendar year, month = 2023, 2 # Remember to keep your calendar up to date! _, last_day = calendar.monthrange(year, month)

And the last piece fits! February's last day:

🧩: [31, **28**, 31, ..., 31]

Your puzzle is now complete!