Home > Software engineering >  How do I loop over an SQL code using Python where the date changes by one month each loop and append
How do I loop over an SQL code using Python where the date changes by one month each loop and append

Time:01-21

I have an SQL query:

select * from db where start date = '2015-01-01'

When I run this it is output as a dataframe. I then require the same SQL statement to run again, but this time the month to increase by 1 (2015-02-01) in the start date and then append this dataframe to the previous, run again with '2015-03-01' and append this dataframe to the previous and keep looping all the way up to 2023-01-01. I then need this to extract this dataframe as a CSV file.

How can I do this in Python?

CodePudding user response:

year = 2015
month = 1
day = 1

for add_month in range(0, 25):
    
    date = f"'{year   add_month // 12}-{month   (add_month % 12):02}-{day:02}'"
    
    sql_query = "select * from db where start date = "  date
    
    print(sql_query)

CodePudding user response:

we could also use the datetime and dateutil module from python. first we create a datetime object from the date string. then we can use relativedelta module to add a time span.

from datetime import datetime
from dateutil.relativedelta import relativedelta

my_date = datetime.strptime('2015-01-01', '%Y-%m-%d')
for repeat in range(0,12):
    print(f"select * from db where start date = '{datetime.strftime(my_date, '%Y-%m-%d')}'")
    my_date = my_date   relativedelta(months= 1)
  • Related