how to get the first day and last day of current month in python
There's a function in the standard library calendar.monthrange(year, month)
:
>>> import calendar
>>> calendar.monthrange(2016, 3)
(1, 31)
Careful, monthrange
doesn't return the dates of first and last days, but returns the weekday of the first day of the month, and number of days in month, for the specified year and month.
So to create first and last date
objects, use 1 for the first day, and the number of days for the second day:
>>> _, 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)
Formatting these as strings:
>>> first_day.strftime('%Y-%m-%d')
'2016-03-01'
>>> last_day.strftime('%Y-%m-%d')
'2016-03-31'