I have a table which has multiple id's, each having different start dates. The end date will remain the same for all and will dynamically change being the last day of the previous month from today's date. I am trying to iterate over each id and respective start date to get a list of months from the start date to the end date mapped back to the id's.
My current table looks like below :
ID Start_Date End_Date
A 2019-12-15 2020-04-30
B 2020-03-03 2020-04-30
My desired output table :
ID Start_Date End_Date ID_period
A 2019-12-15 2020-04-30 201912
A 2019-12-15 2020-04-30 202001
A 2019-12-15 2020-04-30 202002
A 2019-12-15 2020-04-30 202003
A 2019-12-15 2020-04-30 202004
B 2020-03-03 2020-04-30 202003
B 2020-03-03 2020-04-30 202004
I have tried the below code with some changes sourced from Generate list of months between interval in python
from datetime import datetime, timedelta
from collections import OrderedDict
dates = ["2014-10-10","2016-01-01"]
def monthlist_fast(dates):
for val in enumerate(dates):
start = val
end = dt.date.today().replace(day=1) - timedelta(days=1)
start, end = [datetime.strptime(_, "%Y-%m-%d") for _ in dates]
total_months = lambda dt: dt.month + 12 * dt.year
mlist = []
for tot_m in range(total_months(start)-1, total_months(end)):
y, m = divmod(tot_m, 12)
mlist.append(datetime(y, m+1, 1).strftime("%Y%m"))
return mlist
My result:
['201410',
'201411',
'201412',
'201501',
'201502',
'201503',
'201504',
'201505',
'201506',
'201507',
'201508',
'201509',
'201510',
'201511',
'201512',
'201601']
But I am unable to figure out a way to map these back to my Ids especially since my start_dates keep on changing with different Ids. Any help would be appreciated. Thanks.