Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Python Get Last Day of Month
    python

    Python Get Last Day of Month

    April 2, 2023No Comments6 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Day 30 Is Given to Python Every Month

    This Python tutorial will teach you how to calculate the final day of the month from a given date. We will also discuss how to calculate the final day of the next and following months.

    The first day of the month in Python

    .

    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

    There are instances when we need to calculate the final day of the current month. Let’s say you want to develop some code that, given the dateTime value of “2022-8-12,” will return the value “2022-8-31,” i.e. the final day of the month. The procedures outlined below illustrate how to access the calendar module 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

    To Start 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()

    Datetime.replace() and Datetime.timedelta() are useful alternatives to importing the calendar module for a single use case.

    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.

    Let’s examine the procedures involved in accomplishing

    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())

    Produce Results

    :

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

    The first day of the month in Python

    .

    Get The Last Day Of The Month Using dateutil

    To get the last day of a given month, we may also utilize the external library dateutil.

    month.

    Case in Point:

    • 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.

    :

    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())

    Produce Results

    :

    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.

    Illustration

    :

    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())

    Produce Results

    :

    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.

    Illustration

    :

    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())

    Produce Results

    :

    Input date: 2022-09-13
    Last day of the next month: 2022-10-31
    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Get Last Day of Month Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleHTML and CSS for Python Developers
    Next Article Byte Objects vs String in Python

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.