Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the first day and last day of current month in python [duplicate]

Tags:

python

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.

like image 463
Akhil Mathew Avatar asked Mar 22 '16 13:03

Akhil Mathew


People also ask

How do I get the first and last day of the current month in Python?

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.

How do I get start and end date month data from a specific date in Python?

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.

How do you find the first and last day of the current 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.


1 Answers

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'
like image 132
bakkal Avatar answered Oct 19 '22 23:10

bakkal