PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Python Get Last Day of Month

Python Get Last Day of Month

Updated on: October 7, 2022 | Leave a Comment

In this Python lesson, you’ll learn how to find the last day (last date) of a month from a given date. Also, we will cover how to get the last day of next month and the previous month.

Also, see Python Get First Day Of Month.

Table of contents

  • How To Find The Last Day Of The Month In Python
    • Example: Get The Last Day Of The Month
  • Get The Last Day Of The Month Using replace() and timedelta()
    • Example: Get The Last Day Of The Month Using replace() and timedelta()
  • Get The Last Day Of The Month Using dateutil
  • Get Last Day of a Previous Month
  • Get Last Day of a Next Month

How To Find The Last Day Of The Month In Python

Sometimes we need to find the last day of a month from a given date. For example, let’s assume you have a dateTime ‘2022-8-12’ and you want to write a code that will return you 2022-8-31, i.e., the last day of the month or the last date of a month.

The below steps show how to use the calendar module to find the last day of a month in Python.

  1. Import datetime class from a datetime module

    Python datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.

  2. Import calendar module

    This module allows you to output calendars like the Unix cal program and provides additional useful functions related to the calendar. Use the import calendar command to add the calendar module to your script.

  3. Store datetime object in a variable

    Store the original datetime object in a variable for further processing. Or you can use the datetime.today() to get the current datetime if you want to find the last date of a current month.

  4. Use the monthrange() method

    The calendar.monthrange() function returns the weekday of the first day of the month and the number of days in a month, for the specified year and month. In short, it returns a result in tuple format weekday (0-6 ~ Mon-Sun) and number of days (28-31) for provided year and month

    For example, calendar.monthrange(2022, 9) will return (3, 30). i.e., the last day is 30.

Example: Get The Last Day Of The Month

# Get the last day of the month from a given date
import calendar
from datetime import datetime

input_dt = datetime(2022, 9, 13)
print("The original date is:", input_dt.date())

# monthrange() to gets the date range
# year = 2022, month = 9
res = calendar.monthrange(input_dt.year, input_dt.month)
day = res[1]
print(f"Last date of month is: {input_dt.year}-{input_dt.month}-{day}")

# note:
# res [0]  = weekday of first day (between 0-6 ~ Mon-Sun))
# res [1] = last day of the month

Output:

The original date is: 2022-09-13
Last date of month is: 2022-9-30

Get The Last Day Of The Month Using replace() and timedelta()

If you don’t want to import the calendar module just for this use case, you can use the combination of replace() and timedelta() method of a datetime module.

  • datetime.replace(): This method replaces the DateTime object’s contents with the given parameters. This method has various parameters, but here we will use the day parameter because we want to replace the day number of a datetime object with the last day of the month.
  • timedelta(): A timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution. We can use the timedelta to add or subtract weeks, days, hours, minutes, seconds, microseconds, and milliseconds from a given DateTime.

Now, let’s see the steps to achieve the same.

  • First, import the datetime and timedelta class from a datetime module.
  • Next, use the day parameter of a timedelta class to replace the date’s day number with 28 (each month contains at least 28 days).
  • Next, use the timedelta class to add four days to the new date. By doing this, you will get the next month.
  • Now, subtract the number of the current day from the new date to get the last day of a month. (It brings us back to the original month).

Example: Get The Last Day Of The Month Using replace() and timedelta()

from datetime import datetime, timedelta

input_dt = datetime(2022, 9, 13)
print("The original date is:", input_dt.date())

next_month = input_dt.replace(day=28) + timedelta(days=4)
res = next_month - timedelta(days=next_month.day)
print(f"Last date of month is:", res.date())

Output:

The original date is: 2022-09-13
Last date of month is: 2022-09-30

Also, see Python Get First Day Of Month.

Get The Last Day Of The Month Using dateutil

Also, we can use the third-party library dateutil to get the last day of a month.

  • Use pip Install python-dateutil to install it.
  • Next, just add 31 days to your date using the dateutil.relativedelta(day=31) to get the last day of the month.

Example:

from datetime import datetime
from dateutil.relativedelta import relativedelta

input_dt = datetime(2202, 9, 13)
print("The original date is:", input_dt.date())

# add 31 days to the input datetime
res = input_dt + relativedelta(day=31)
print(f"Last date of month is:", res.date())

Output:

The original date is: 2202-09-13
Last date of month is: 2202-09-30

Get Last Day of a Previous Month

  • Import the datetime and timedelta class from a datetime module
  • First, calculate the first day of a month using res = input_dt.replace(day=1).
  • Now, use the timedelta class to subtract one day from the resultant date to get the last day of the previous month.

Example:

from datetime import datetime, timedelta

input_dt = datetime(2022, 9, 13)
first = input_dt.replace(day=1)
print('first day of a month:', first.date())

res = first - timedelta(days=1)
print('Last day of a previous month is:', res.date())

Output:

first day of a month: 2022-09-01
Last day of a previous month is: 2022-08-31

Get Last Day of a Next Month

  1. Import the datetime and timedelta class from a datetime module
  2. Next, use the day parameter of a timedelta class to replace the date’s day number with the 28 (because each month contains at least 28 days) to move to the next month
  3. Next, use the timedelta class to add four days to the new date. By doing this, you will get the next month.
  4. Repeat the 2 and 3 steps to get the second next month.
  5. Now, use the timedelta class to subtract one day from the resultant date to get the last day of the next month.

Example:

from datetime import datetime, timedelta

input_dt = datetime(2022, 9, 13)
print('Input date:', input_dt.date())

# move to first next month
next_month = input_dt.replace(day=28) + timedelta(days=4)

# Now move to the second next month
next_month = next_month.replace(day=28) + timedelta(days=4)

# come back to the first next month's last day
res = next_month - timedelta(days=next_month.day)
print('Last day of the next month:', res.date())

Output:

Input date: 2022-09-13
Last day of the next month: 2022-10-31

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

Posted In

Python Python DateTime
TweetF  sharein  shareP  Pin

  Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com