How to get the first day and last day of the current month in python

I am writing an SQL query to get available data between the first date and the last date of the current month in python. For this, how can I get the first and last date of the current month. (The question that has already been asked in stackoverflow concerns only the end date. I also want the answer to be like a date field, for example 01-03-2016 or 31-03-2016 )

+5
source share
1 answer

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

There is a function in the standard lib calendar.monthrange(year, month)

 >>> import calendar >>> calendar.monthrange(2016, 3) (1, 31) 

Caution , monthrange does not return the dates of the first and last days, but returns the day of the week of the first day of the month and the number of days in the month for the specified year and month.

So, to get the objects of the first and last date from 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) 

Line format

 >>> first_day.strftime('%d-%m-%Y') '01-03-2016' >>> last_day.strftime('%d-%m-%Y') '31-03-2016' 
+14
source

Source: https://habr.com/ru/post/1245553/


All Articles