Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here is my code:

import datetime

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

date_counter = 0
while not date == today:
    date_counter+=1
    date += oneday

In this code I use while loop to achieve my goal--to count the days between today and the specific day chosen by users.

However, I want to use for loop to do the same thing. Can it rewrite by for?

like image 564
Mars Lee Avatar asked Mar 09 '16 07:03

Mars Lee


People also ask

How do you add one day to a datetime object?

Add Days to datetime Object If we want to add days to a datetime object, we can use the timedelta() function of the datetime module.

How do you loop a date?

Using a while Loop Then we can increment the start date until it reaches the end date. We have the start and end variables with the start and end date respectively. Then we create the loop variable that we use as the looping variable. We increment the date of loop until it reaches end .


1 Answers

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)
like image 72
NighttimeDriver50000 Avatar answered Oct 02 '22 12:10

NighttimeDriver50000