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.
There are a few ways to do this, but I've gone with the following: last_date = datetime(year, month + 1, 1) + timedelta(days=-1) . This will calculate the first date of the following month, then subtract 1 day from it to get the last date of the current month.
You can use current_date. replace(day=1) to get first day in current month. And if you substract datetime. timedelta(days=1) then you get last day in previous month.
To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With