How to use for loop and add one day (timedelta) every time

Subtraction of dates makes a timedelta:

import datetime
date = datetime.date(2015,10,1)
today = datetime.date.today()
date_counter = (today - date).days

If you really want to use a for loop, however, you can do this:

import datetime

date = datetime.date(2015,10,1)
today = datetime.date.today()
one_day = datetime.timedelta(days=1)

date_counter = 0

def gen_dates(some_date):
    while some_date != today:
        some_date += one_day
        yield some_date

for d in gen_dates(date):
    date_counter += 1
    print(date_counter, ':', d)

The approach that you are using is not advised. The better approach would be to not use a loop in the first place. You can instead try the following code:

import datetime

date = datetime.date(2015,10,1)
today = datetime..today()
oneday = datetime.timedelta(days = 1)

date_counter = (today - date).days

To answer your question about possibility of using for loop. I would say a big no. hope this helps.


The following code only makes sense if you want to do something for every day in this range.

import datetime

date = datetime.date(2016,2,1)
today = datetime.date.today()
oneday = datetime.timedelta(days = 1)

date_counter = 0
for days in range(0, (today - date).days):
     date_counter += 1
     date += oneday

If you only need the number of days you can use this

date_counter = (today - date).days