Home > OS >  how to iterate over date using for loop in python
how to iterate over date using for loop in python

Time:01-19

I am creating an app where I have two values, a committee starting date for e-g 2022,01,02 and for how many months it will continue here it is (4months). Now I am saving some data in my database month wise and also these dates will save too. now the issue is I am getting right result if the number of month is less than or equal to 12 using this.

number of memebrs = 12
starting date = 2022,01,01
for i in range(1,17):
      print('date', (2022,i,10))

but the issue comes when the months are greater than 12 so than date start printing 2022,01,13 which is false because I also want to increment the year to 2023, I feel like this is not really a good idea very inefficient looking way. can anyone tell me is there any other way to do this.

CodePudding user response:

While you can use the datetime library to handle dates, it doesn't provide any methods to increase dates month by month.

Now, previous suggestions/answers suggest you increase the year when month == 12, but that will cause December to be skipped. Also, your code doesn't consider any given month in the starting date. So a better solution would be:

>>> year = 2022
>>> month = 7
>>> day = 23
>>>
>>> for i in range(1, 8):
...     month  = 1
...     if month == 13:
...         month = 1
...         year  = 1
...     print(f'{year}-{month}-{day}')
...
2022-8-23
2022-9-23
2022-10-23
2022-11-23
2022-12-23
2023-1-23
2023-2-23

CodePudding user response:

you could do something like this:

date = [2022,1,10]
for i in range(1,17):
    if i==0:
        date[0] =1
        date[1]=1
    print('date', (time[0],i,time[2]))

CodePudding user response:

By the tone of your question i think you are a beginner, so i won't recommend you to use datetime module and i appreciate that you tried to do it on your own. What i dont appreciate is that why cant you just use if statements and create variables for year and date

yr = 2022
dt = 1
for i in range(1,17):
  print('date', (yr,i,dt))
  if i % 12 == 0:
    yr  = 1
    mn = 1

I also want to share the modern aproach using datetime module. But it requires some modules.

In your cmd enter the command pip install python-dateutil

Once installed close cmd and refresh your ide

this is the code you may want to use

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_time = datetime(2022, 1, 1) #Creating a Date object

for i in range(1, 17):
    date = date_time.date()
    print(date)
    date_time = date_time   relativedelta(months=1)
  •  Tags:  
  • Related