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\" #
With pandas, you can have a one liner like this:
import pandas as pd
date1 = "2014-10-10" # input start date
date2 = "2016-01-07" # input end date
month_list = [i.strftime("%b-%y") for i in pd.date_range(start=date1, end=date2, freq='MS')]
here is the similar version of what Pynchia suggestioned, the below implementation is for python 3.8 the one he implemented is for python 2.x
import datetime
st="2020-06-24"
ed="2020-11-24"
start_date = datetime.datetime.strptime(st.strip(), '%Y-%m-%d')
end_date = datetime.datetime.strptime(ed.strip(), '%Y-%m-%d')
months = [datetime.datetime.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y')
for y in range(start_date.year, end_date.year + 1)
for m in range(start_date.month if y == start_date.year else 1, end_date.month + 1 if y == end_date.year else 13)]
print(months)
Here is my solution with a simple list comprehension which uses range
to know where months must start and end
from datetime import datetime as dt
sd = dt.strptime('2014-10-10', "%Y-%m-%d")
ed = dt.strptime('2016-01-07', "%Y-%m-%d")
lst = [dt.strptime('%2.2d-%2.2d' % (y, m), '%Y-%m').strftime('%b-%y') \
for y in xrange(sd.year, ed.year+1) \
for m in xrange(sd.month if y==sd.year else 1, ed.month+1 if y == ed.year else 13)]
print lst
produces
['Oct-14', 'Nov-14', 'Dec-14', 'Jan-15', 'Feb-15', 'Mar-15', 'Apr-15', 'May-15', 'Jun-15', 'Jul-15', 'Aug-15', 'Sep-15', 'Oct-15', 'Nov-15', 'Dec-15', 'Jan-16']
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,
)
)