Ask Your Question
4

How can I obtain a list of every month that falls between two given dates?

asked 2023-06-23 10:28:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-23 10:37:02 +0000

woof gravatar image

Here's a Python code that can generate a list of every month that falls between two given dates:

from datetime import datetime, timedelta
def get_month_list(start_date, end_date):
    start_month = datetime.strptime(start_date, '%Y-%m-%d').date().replace(day=1)
    end_month = datetime.strptime(end_date, '%Y-%m-%d').date().replace(day=1)

    month_list = []
    while start_month <= end_month:
        month_list.append(start_month.strftime('%B %Y'))
        if start_month.month == 12:
            start_month = start_month.replace(year=start_month.year+1, month=1)
        else:
            start_month = start_month.replace(month=start_month.month+1)

    return month_list

The input parameters should be two strings in the format of 'yyyy-mm-dd' representing the start and end dates. The function returns a list of month-year strings (e.g. ['January 2022', 'February 2022', 'March 2022']).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-23 10:28:00 +0000

Seen: 16 times

Last updated: Jun 23 '23