I am writing an SQL query to get the available data between the first date and last date of the current month in python. For this how can I get first and last date of current month. (In the question that already asked in stackoverflow only deals with end date. Also I want the answer as a date field like 01-03-2016 or 31-03-2016)
how to get the first day and last day of current month in python
There's a function in the standard lib
>>> import calendar >>> calendar.monthrange(2016, 3) (1, 31)
monthrange doesn't return the dates of first and last days, but returns weekday of first day of the month and number of days in month, for the specified year and month.
So to get first and last date objects out of 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)
>>> first_day.strftime('%d-%m-%Y') '01-03-2016' >>> last_day.strftime('%d-%m-%Y') '31-03-2016'