简体   繁体   中英

Add days and loop over dates for a number of weeks

I did this,

>>> d1 = datetime.date(2018, 7, 26)
>>> d2 = datetime.date(2018, 10, 14)
>>> dif = d2 - d1
>>> start_mon =(d1 - datetime.timedelta(days=d1.weekday()))
>>> num_of_weeks = math.ceil((d2 - start_mon).days / 7.0)
>>> num_of_weeks
12
>>>xp = [d1 + datetime.timedelta(i) for i in range( math.ceil((D2 - start_mon).days / 7.0))]
>>> [datetime.date(2018, 7, 26), datetime.date(2018, 7, 27), datetime.date(2018, 7, 28), datetime.date(2018, 7, 29), datetime.date(2018, 7, 30), datetime.date(2018, 7, 31), datetime.date(2018, 8, 1), datetime.date(2018, 8, 2), datetime.date(2018, 8, 3), datetime.date(2018, 8, 4), datetime.date(2018, 8, 5), datetime.date(2018, 8, 6)]

I want python to give me the weekdays between 12 weeks. So since the start date is 2018-07-26, the next date should be 2018-08-02, next should also be 2018-07-09 till it ends at 2018-10-11 . and if if after count it's 12 weeks.

eg

2018-07-26
2018-08-02
2018-08-09
2018-08-16
2018-08-23 
2018-08-30 
2018-09-06 
2018-09-13 
2018-09-20 
2018-09-27 
2018-10-04 
2018-10-11

what am I missing?

You can use a while loop, adding 7 days with each pass.

xp = [d1]
while (d2 - d1).days > 7:
    d1 += datetime.timedelta(7)
    xp.append(d1)

In-place addition works in this case because datetime objects are immutable.

Here another try :

import datetime

d1 = datetime.date(2018, 7, 26)
d2 = datetime.date(2018, 10, 14)

days = d1
while days < d2:
    print(days)
    days += datetime.timedelta(7)

I also used this function.

>>> def next_days(st_date, end_date):
    if st_date <= end_date:
        print (st_date.strftime("%Y-%m-%d"))
        next_date = st_date + timedelta(days=7)
        next_days(next_date, end_date)


>>> st_date = datetime.date(2018, 7, 26)
>>> end_date = datetime.date(2018, 10, 14)
>>> next_days(st_date, end_date)

)

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