简体   繁体   中英

create a list of dates with a while loop python

I want tot create a list of dates starting from 10/09/2020 with increments of 182 days until reaching 05/03/2020.

my code is this:

start_date="10/09/2020" 
last_date="05/03/2020"
start_date=datetimedatetime.strptime(date,"%d/%m/%Y").date()    
last_date=datetimedatetime.strptime(date,"%d/%m/%Y").date()
dates=[]
while dates[-1] != last_date:
    i=star_date+timedelta(days=182)
    dates.append(i)
    dates[i]=i+timedelta(days=pago_cupon)

I don't know what's your problem. You can try this code

from datetime import date, timedelta

start_day = date(year=2020, month=9, day=10)
end_day = date(year=2021, month=3, day=5)
one_data_delta = timedelta(days=1)
res = []

while end_day != start_day:
    start_day += one_data_delta
    res.append(start_day)

print(res)

A few problems:

  1. You had a spelling mistake in your for loop star_date instead of start_date .
  2. Also, you may want to change the comparison from != to less than equals or more than equals.
  3. I am checking against (last_date - timedelta(days=182)) so that we won't exceed the last_date.
  4. Your original start date is after your original end date.
  5. As an example, I have adjusted the end day to be a couple years in the future.
  6. I'm appending the dates as text.
from datetime import datetime, timedelta
start="10/09/2020" 
last="05/03/2022"
start_date=datetime.strptime(start,"%d/%m/%Y")
last_date=datetime.strptime(last,"%d/%m/%Y")
dates=[]
while start_date <= (last_date - timedelta(days=182)):
    start_date += timedelta(days=182)
    dates.append(start_date.strftime("%d/%m/%Y"))
    # not quite sure what you are trying to do here:
    #dates[i]=i+timedelta(days=pago_cupon)
print(dates)

Output:

['11/03/2021', '09/09/2021']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM