Мы можем сделать это, используя комбинацию datetime и календарь модулей в python
def get_start_end_dates(from_date, to_date):
# Convert string to datetime objects
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d')
to_date = datetime.datetime.strptime(to_date, '%Y-%m-%d')
# The beginning day is always 1
beg_date = datetime.datetime(from_date.year, from_date.month, 1)
# Iterate till the beginning date is less the to date
while beg_date <= to_date:
# Get the number of days in that month in that year
n_days_in_that_month = calendar.monthrange(beg_date.year, beg_date.month)[1]
# Get end date using n_days_in_that_month
end_date = datetime.datetime(beg_date.year, beg_date.month, n_days_in_that_month)
# Yield the beg_date and end_date
yield (beg_date.date(), end_date.date())
# Next month's first day will be end_date + 1 day
beg_date = end_date + datetime.timedelta(days=1)
for period_start, period_end in get_start_end_dates('2018-02-01', '2019-01-01'):
print ('period_start: {}'.format(period_start), 'period_end: {}'.format(period_end))
Результат для приведенного выше кода выглядит следующим образом.
period_start: 2018-02-01 period_end: 2018-02-28
period_start: 2018-03-01 period_end: 2018-03-31
period_start: 2018-04-01 period_end: 2018-04-30
period_start: 2018-05-01 period_end: 2018-05-31
period_start: 2018-06-01 period_end: 2018-06-30
period_start: 2018-07-01 period_end: 2018-07-31
period_start: 2018-08-01 period_end: 2018-08-31
period_start: 2018-09-01 period_end: 2018-09-30
period_start: 2018-10-01 period_end: 2018-10-31
period_start: 2018-11-01 period_end: 2018-11-30
period_start: 2018-12-01 period_end: 2018-12-31
period_start: 2019-01-01 period_end: 2019-01-31
Надеюсь, это поможет!