## Python cookbook 3rd note (3.14): calculating the date range of the current month

Giant ship 2020-11-19 04:08:19
python cookbook 3rd rd note

# Calculate the date range of the current month

## problem

Your code needs to cycle through the current month every day , Want to find an efficient way to calculate this date range .

## solution

Loop over such dates and construct a list of all dates in advance . You can calculate the start date and the end date first , Then use it as you step datetime.timedelta Object to increment the date variable .

Here is an acceptance of arbitrary datetime Object and returns a tuple object consisting of the start of the current month and the start of the next month .

``````from datetime import datetime, date, timedelta
import calendar
def get_month_range(start_date=None):
if start_date is None:
start_date = date.today().replace(day=1)
_, days_in_month = calendar.monthrange(start_date.year, start_date.month)
end_date = start_date + timedelta(days=days_in_month)
return (start_date, end_date)
``````

With this, it's easy to loop over the returned date range ：

``````>>> a_day = timedelta(days=1)
>>> first_day, last_day = get_month_range()
>>> while first_day < last_day:
... print(first_day)
... first_day += a_day
...
2012-08-01
2012-08-02
2012-08-03
2012-08-04
2012-08-05
2012-08-06
2012-08-07
2012-08-08
2012-08-09
#... and so on...
``````

## Discuss

The above code first calculates a date corresponding to the first day of the month . A quick way is to use date or datetime Object's replace() The method is simple days Property set to 1 that will do . replace() One of the advantages of the method is that it creates objects of the same type that you started to pass in . therefore , If the input parameter is a date example , So the result is also a date example . alike , If the input is a datetime example , So what you get is a datetime example .

then , Use calendar.monthrange() Function to find the total number of days in the month . Whenever you want to get calendar information , that calendar Modules are very useful . monthrange() The function returns a tuple containing the days of the week and the month .

Once the days of the month are known , Then the end date can be obtained by adding this number of days to the start date . It should be noted that the end date is not included in this date range ( In fact, it's the start date of next month ). This and Python Of slice And range Operation behavior is consistent , It also doesn't contain the end .

To loop through the date range , To use standard math and comparison operations . such as , You can use timedelta Instance to increment the date , Less than no. < Used to check whether a date is before the end date .

Ideally , If you can create a date iteration with the built-in range() It's just like a function . Fortunately, , You can use a generator to achieve this goal easily ：

``````def date_range(start, stop, step):
while start < stop:
yield start
start += step
``````

Here's an example of using this generator ：

``````>>> for d in date_range(datetime(2012, 9, 1), datetime(2012,10,1),
timedelta(hours=6)):
... print(d)
...
2012-09-01 00:00:00
2012-09-01 06:00:00
2012-09-01 12:00:00
2012-09-01 18:00:00
2012-09-02 00:00:00
2012-09-02 06:00:00
...
>>>
``````

The reason why this implementation is so simple , Thanks to it Python The date and time in can be calculated using standard mathematical and comparison operators .