Untitled

mail@pastecode.io avatarunknown
plain_text
a month ago
971 B
1
Indexable
Never
from datetime import datetime, timedelta
from typing import List

def get_first_dates_of_each_month(start_dt: str, end_dt: str) -> List[str]:
    start_date = datetime.strptime(start_dt, '%Y-%m-%d')
    end_date = datetime.strptime(end_dt, '%Y-%m-%d')
    
    # Adjusting the start date to the first of the month
    start_date = start_date.replace(day=1)
    
    dates_list = []

    while start_date <= end_date:
        dates_list.append(start_date.strftime('%Y-%m-%d'))
        if start_date.month == 12:  # if current month is December, go to the next year
            start_date = start_date.replace(year=start_date.year + 1, month=1)
        else:
            start_date = start_date.replace(month=start_date.month + 1)

    return dates_list

# Test
start_dt1 = '2023-02-01'
end_dt1 = '2023-05-01'
print(get_first_dates_of_each_month(start_dt1, end_dt1))

start_dt2 = '2023-02-28'
end_dt2 = '2023-05-17'
print(get_first_dates_of_each_month(start_dt2, end_dt2))