1from datetime import date, timedelta
2
3last_day_of_prev_month = date.today().replace(day=1) - timedelta(days=1)
4
5start_day_of_prev_month = date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
6
7# For printing results
8print("First day of prev month:", start_day_of_prev_month)
9print("Last day of prev month:", last_day_of_prev_month)
1>>import calendar
2>>year, month = 2016, 12
3>>calendar.monthrange(year, month)[1]
431
5
1import calendar
2from datetime import datetime
3
4year = 2020
5month = 1
6
7rng = calendar.monthrange(year, month) # (2, 31)
8last_day = datetime(year, month, rng[1])
9
10# calendar.monthrange returns tuple in the format of
11# (<day of week>, <last day>). day of week is 0 indexed
12# starting on Monday
13#
14# 0 = Monday
15# 1 = Tuesday
16# 2 = Wednesday
17# 3 = Thursday
18# 4 = Friday
19# 5 = Saturday
20# 6 = Sunday
21