how to get the first day and last day of the current month in python
There is a function in the standard lib calendar.monthrange(year, month)
>>> import calendar >>> calendar.monthrange(2016, 3) (1, 31)
Caution , monthrange
does not return the dates of the first and last days, but returns the day of the week of the first day of the month and the number of days in the month for the specified year and month.
So, to get the objects of the first and last date from it:
>>> _, num_days = calendar.monthrange(2016, 3) >>> first_day = datetime.date(2016, 3, 1) >>> last_day = datetime.date(2016, 3, num_days) >>> first_day datetime.date(2016, 3, 1) >>> last_day datetime.date(2016, 3, 31)
Line format
>>> first_day.strftime('%d-%m-%Y') '01-03-2016' >>> last_day.strftime('%d-%m-%Y') '31-03-2016'
source share