pythonpandasdatedatetimeranged-loops

Iterate over the next 12 months from today using Python


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.

  1. I created a FOR LOOP but I am stuck on the fact that it does not store the range in the list.
  2. I got a Value Error: Month must be in 1..12 so I'm stuck as well. Can I get help with either?
# 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)

Solution

  • 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'])