I am trying to write python code that takes the first of the next month and creates a dataframe of the next 12 months. I have tried two ways to which did not work.
# FIRST TRY
# import packages
# python
import pandas as pd
import numpy as np
import datetime as dt
from datetime import timedelta
from datetime import datetime
from datetime import date
from dateutil.relativedelta import relativedelta
#get todays date
today = dt.date.today()
# Get the first day of next month
first_day_next_month = (today.replace(day=1) + dt.timedelta(days=32)).replace(day=1)
# Get the first day of the next 12 months
first_day_next_12_months = []
for i in range(1, 13):
next_month = first_day_next_month + relativedelta(months=i)
first_day_next_12_months.append(next_month)
print(first_day_next_12_months)
#SECOND TRY
# import packages
# python
import pandas as pd
import numpy as np
import datetime as dt
from datetime import timedelta
from datetime import datetime
from datetime import date
from dateutil.relativedelta import relativedelta
#get todays date
today = dt.date.today()
# Get the first day of next month
first_day_next_month = (today.replace(day=1) + dt.timedelta(days=32)).replace(day=1)
# Get the first day of next month
first_day_next_month = (today.replace(day=1) + dt.timedelta(days=32)).replace(day=1)
print("First day of next month:", first_day_next_month)
# Get the first day of the next 12 months
first_day_next_12_months = []
for i in range(1, 13):
next_month = (first_day_next_month.replace(month=first_day_next_month.month + i-1) + datetime.timedelta(days=32)).replace(day=1)
first_day_next_12_months.append(next_month)
print("First day of the next 12 months:")
for date in first_day_next_12_months:
print(date)
If working with pandas.DataFrame
, you mostly don't need for
loops.
Just do :
import pandas as pd
import datetime as dt
from dateutil.relativedelta import relativedelta
today = dt.date.today()
first_day_next_month = (today.replace(day=1) + relativedelta(months=1))
first_day_next_12_months = [first_day_next_month + relativedelta(months=i) for i in range(12)]
df_months = pd.DataFrame(first_day_next_12_months, columns=['First Day of Month'])