Generate list of months between interval in python

后端 未结 10 1197
庸人自扰
庸人自扰 2020-12-08 02:14

I want to generate a python list containing all months occurring between two dates, with the input and output formatted as follows:

date1 = \"2014-10-10\"  #         


        
10条回答
  •  我在风中等你
    2020-12-08 03:01

    I came to a solution that uses python-dateutil and works with Python 3.8+:

    https://gist.github.com/anatoly-scherbakov/593770d446a06f109438a134863ba969

    def month_range(
        start: datetime.date,
        end: datetime.date,
    ) -> Iterator[datetime.date]:
        """Yields the 1st day of each month in the given date range."""
        yield from itertools.takewhile(
            lambda date: date < end,
            itertools.accumulate(
                itertools.repeat(relativedelta(months=1)),
                operator.add,
                initial=start,
            )
        )
    

提交回复
热议问题