Created
April 5, 2020 07:02
-
-
Save anatoly-scherbakov/593770d446a06f109438a134863ba969 to your computer and use it in GitHub Desktop.
Months range
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import itertools | |
import functools | |
from typing import Iterator | |
import datetime | |
from dateutil.relativedelta import relativedelta | |
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, | |
) | |
) | |
if __name__ == '__main__': | |
print(list(month_range( | |
datetime.date(2017, 1, 1), | |
datetime.date(2018, 3, 4), | |
))) | |
# [ | |
# datetime.date(2017, 1, 1), datetime.date(2017, 2, 1), datetime.date(2017, 3, 1), datetime.date(2017, 4, 1), | |
# datetime.date(2017, 5, 1), datetime.date(2017, 6, 1), datetime.date(2017, 7, 1), datetime.date(2017, 8, 1), | |
# datetime.date(2017, 9, 1), datetime.date(2017, 10, 1), datetime.date(2017, 11, 1), datetime.date(2017, 12, 1), | |
# datetime.date(2018, 1, 1), datetime.date(2018, 2, 1), datetime.date(2018, 3, 1) | |
# ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I attempted to replace
lambda date: date < end
withfunctools.partial(operator.le, b=end)
butoperator.le
does not treatb
as a keyword argument. Not sure if that is possible.P. S. This requires Python 3.8 due to
initial=
argument foritertools.accumulate()
.