Python program to find Last date of Month
Last Updated :
15 Apr, 2023
Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month.
Examples:
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
import datetime
test_date = datetime.datetime( 2018 , 6 , 4 )
print ( "The original date is : " + str (test_date))
nxt_mnth = test_date.replace(day = 28 ) + datetime.timedelta(days = 4 )
res = nxt_mnth - datetime.timedelta(days = nxt_mnth.day)
print ( "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
from datetime import datetime
import calendar
test_date = datetime( 2018 , 6 , 4 )
print ( "The original date is : " + str (test_date))
res = calendar.monthrange(test_date.year, test_date.month)[ 1 ]
print ( "Last date of month : " + str (res))
|
Output:
The original date is : 2018-06-04 00:00:00
Last date of month : 30
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #3 : Using reduce():
Algorithm:
- Import required modules – datetime, calendar and reduce.
- Initialize a test date using datetime.
- Pass the year and month of the test date to monthrange() function of the calendar module to get the range of days in the month.
- Use reduce() function to extract the last date of the month from the returned tuple.
- Print the original date and the last date of the month.
Python3
from datetime import datetime
import calendar
from functools import reduce
test_date = datetime( 2018 , 6 , 4 )
res = reduce ( lambda x, y: y[ 1 ], [calendar.monthrange(test_date.year, test_date.month)], None )
print ( "The original date is : " + str (test_date))
print ( "Last date of month : " + str (res))
|
Output
The original date is : 2018-06-04 00:00:00
Last date of month : 30
Time Complexity: O(1) since there is a fixed number of operations performed, regardless of the size of input.
Space Complexity: O(1) since we are only storing the test date, month range and the result variable
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...