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?
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.
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 .
Subtraction of date
s 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With