Last day in month python

How to Get the Last Day of the Month using a specific Date in Python

In this article, we will learn how to get the last day of the month using a date in python.

There are many ways to get or find the last day of the month using a specific date in python. Here is some example as follows:

Example 1: In this example, we will use date.replace() and monthrange() method to get the last day of the month using a specific date in python.

Example 1
#Import Modules from datetime import datetime from calendar import monthrange def last_day_of_month(date_value): return date_value.replace(day = monthrange(date_value.year, date_value.month)[1]) given_date = datetime.today().date() print("\nLast day of month:", last_day_of_month(given_date)) # output ==> Last day of month: 2020-03-31 given_date = datetime(year=2020, month=2, day=1).date() print("\nLast day of month:", last_day_of_month(given_date)) # Output ==> Last day of month: 2020-02-29 

Example 2: In this example, we will use only the d atetime module and If you don’t want to import the calendar module , then you can use a simple two-step function to get the last day of the month using a specific date in python.

Example 2
# Import Module import datetime def last_day_of_month(any_day): next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail return (next_month - datetime.timedelta(days=next_month.day)).strftime('%Y-%m-%d') print("\nLast Day of Month: ", last_day_of_month(datetime.date(2020, 3, 1))) #Output ==> Last Day of Month: 2020-03-31 print("\nLast Day of Month: ", last_day_of_month(datetime.datetime.now())) #Output ==> Last Day of Month: 2020-03-31 

Example 3: In this example, we will use the timedelta module from datetime module and date.replace() method to get the last day of the month using a specific date in python.

Example 3
#Import Module from datetime import timedelta def last_day_of_month(date): Last_day=(date.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1) return Last_day print("\nLast Day of Month: ", last_day_of_month(datetime.date(2020, 3, 1))) #Output ==> Last Day of Month: 2020-03-31 

Example 4: In this example, we will extract the date part from the date.

Example 4
# Import Module import datetime def last_day_of_month(date): year=date.year # Extract Year From Date month=date.month # Extract Month From Date Last_day = datetime.date(year + int(month/12), month%12+1, 1)-datetime.timedelta(days=1) return Last_day print("\nLast Day of Month: ", last_day_of_month(datetime.date(2020, 2, 1))) # Output ==> Last Day of Month: 2020-02-29 

Example 5: Here is another example to get the last day of the month using a specific date in python.

Example 5
# Import Module import datetime def last_day_of_month(date): first_day_of_month = datetime.datetime(date.year, date.month, 1) next_month_date = first_day_of_month + datetime.timedelta(days=32) new_dt = datetime.datetime(next_month_date.year, next_month_date.month, 1) Last_day= new_dt - datetime.timedelta(days=1) return Last_day.strftime('%Y-%m-%d') print("\nLast Day of Month: ", last_day_of_month(datetime.date(2020, 2, 1))) #Output ==> Last Day of Month: 2020-02-29 

Example 6: Here is another example to get the last day of the month using a specific date in python. In this example, we will use monthlen() import from calendar module.

Читайте также:  Start bat для css
Example 6
# Import Module import datetime import calendar def last_day_of_month(date): Last_day = datetime.datetime(date.year, date.month,calendar.monthlen(date.year, date.month) ) return Last_day.strftime('%Y-%m-%d') print("\nLast Day of Month: ", last_day_of_month(datetime.date(2020, 2, 25))) #Output ==> Last Day of Month: 2020-02-29 print("\nLast Day of Month: ", last_day_of_month(datetime.date(2019, 2, 25))) #Output ==> Last Day of Month: 2019-02-28 

I hope this article will help you to understand how to get the last day of the month using a date in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!

Источник

Python Get Last Day of Month

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.

Table of contents

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 modulePython 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

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: --") # note: # res [0] = weekday of first day (between 0-6 ~ Mon-Sun)) # res [1] = last day of the month
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())
The original date is: 2022-09-13 Last date of month is: 2022-09-30

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.
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())
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.
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())
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.
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())
Input date: 2022-09-13 Last day of the next month: 2022-10-31

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

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

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

Источник

Get last day of month in Python

Last day of month in Python

In this article, we will discuss how to find the last day of the month in Python using different modules.

Using the calendar.monthrange() function

The monthrange() function is used to return a tuple containing the first weekday of the month and the total number of days in the month. We have to pass the year and month to this function.

After getting the above mentioned values, we will create a new date object using the given date and use the replace() function to replace the day number with the total number of days in that month.

For Python 3.7 and above, we can also use the monthlen() function from this module which returns the total number of days in a month.

Using the dateutil.relativedelta() function

The dateutil can be considered as an extension to the datetime module. Both these modules are very often used together and the dateutil module provides a vast range of functionalities to operate on datetime objects. We can use the relativedelta() function to compute the last date of the month from a given date.

The above code gives the last date of the month in a datetime object.

Using the datetime module

We can create our own little function to return the last day of the month using the datetime module. This method can be considered unconventional but provides the desired result. Basically, we calculate the first day of the next month from a given date, then we subtract 1 day from this date and we get the date of the last day of the month.

The following code implements the above method.

d = datetime . date ( year + int ( month / 12 ) , month % 12 + 1 , 1 ) — datetime . timedelta ( days = 1 )

0 here indicates that the day is Monday.

Using the pandas.end_time() function

The pandas module deals very frequently with data containing dates and time values. That is why it is equipped with different functions that can work with such values. It is not advisable to use methods from this module unless one is working with DataFrames.

The end_time() function can return the final date and time of a given period. We can specify the date and set frequency to ‘M’, and we will get the final date of the month.

Источник

Оцените статью