11

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.

Note: 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.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Akhil Mathew
  • 1,571
  • 3
  • 34
  • 69

1 Answers1

33

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'
bakkal
  • 54,350
  • 12
  • 131
  • 107