Python program to find Last date of Month
Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month.
Examples:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Input : test_date = datetime.datetime(2018, 6, 4)
Output : 30
Explanation : April has 30 days, each year
Input : test_date = datetime.datetime(2020, 2, 4)
Output : 29
Explanation : February had 29 days in 2020, leap year.
Method #1 : Using replace() + timedelta()
In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.
Python3
# Python3 code to demonstrate working of# Get Last date of Month# Using replace() + timedelta()import datetime# initializing datetest_date = datetime.datetime(2018, 6, 4) # printing original dateprint("The original date is : " + str(test_date))# getting next month# using replace to get to last day + offset# to reach next monthnxt_mnth = test_date.replace(day=28) + datetime.timedelta(days=4)# subtracting the days from next month date to# get last date of current Monthres = nxt_mnth - datetime.timedelta(days=nxt_mnth.day)# printing resultprint("Last date of month : " + str(res.day)) |
Output:
The original date is : 2018-06-04 00:00:00 Last date of month : 30
Method #2 : Using calendar()
This uses an inbuilt function to solve this problem. In this, given year and month, the range can be computed using monthrange() and its second element can get the result required.
Python3
# Python3 code to demonstrate working of# Get Last date of Month# Using calendar()from datetime import datetimeimport calendar# initializing datetest_date = datetime(2018, 6, 4) # printing original dateprint("The original date is : " + str(test_date))# monthrange() gets the date range# required of monthres = calendar.monthrange(test_date.year, test_date.month)[1]# printing resultprint("Last date of month : " + str(res)) |
Output:
The original date is : 2018-06-04 00:00:00 Last date of month : 30


