Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I divide a date range into months in Python?

I have the following date range:

begin: 2018-02-15
end: 2018-04-23

I want to achieve the following:

["2018-02-15 - 2018-02-28", "2018-03-01 - 2018-03-31", "2018-04-01 - 2018-04-23"]

Essentially, I want to divide a given date range into months. I can't think of a way to accomplish this in Python.

I have considered the solution here, however, this splits the date range based on a specified interval. I want to be able to split a date range dynamically.

Hence, given a date range from 15 February 2018 to 23 April 2018, I want to be able to get the individual months in the range, like so:

  • 15 February 2018 to 28 February 2018
  • 01 March 2018 to 31 March 2018
  • 01 April 2018 to 23 April 2018
like image 434
Brandon Chetty Avatar asked Dec 11 '22 06:12

Brandon Chetty


1 Answers

In a loop; starting at the first day continually add one day till you get to the end date; whenever the month changes save the dates.

import datetime
begin = '2018-02-15'
end = '2018-04-23'

dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
    #print(today)
    tomorrow = today + one_day
    if tomorrow.month != today.month:
        start_dates.append(tomorrow)
        end_dates.append(today)
    today = tomorrow

end_dates.append(dt_end)


out_fmt = '%d %B %Y'
for start, end in zip(start_dates,end_dates):
    print('{} to {}'.format(start.strftime(out_fmt), end.strftime(out_fmt)))

Result:

>>>
15 February 2018 to 28 February 2018
01 March 2018 to 31 March 2018
01 April 2018 to 23 April 2018
>>>

You could probably figure out a way to get a range of months between the start and end dates; create a datetime object for the first day of each of those months store them and the days just prior to them. Dates spanning a change of year might be problematic though.

like image 187
wwii Avatar answered Dec 29 '22 19:12

wwii