pythonarraysdaterangedelta

Exclude specific dates from date range - Python


I tried to exclude specific dates from a range of date and not getting valid output and below is the code. Could you please help to fix it.

from datetime import timedelta, date

sdate = date(2020, 7, 1)
edate = date(2020, 7, 7)
delta = edate - sdate

toRemoveDate = [date(2020, 7, 6), date(2020, 7, 2)]

for i in range(delta.days + 1):
    day = sdate + timedelta(days=i)
    print(day)

    for j in range(len(toRemoveDate)):
        if day != toRemoveDate[j]:
            print(day)

Thanks, Anand


Solution

  • try this,

    from datetime import timedelta, date
    
    sdate = date(2020, 7, 1)
    edate = date(2020, 7, 7)
    delta = edate - sdate
    
    toRemoveDate = [date(2020, 7, 6), date(2020, 7, 2)]
    
    for i in range(delta.days + 1):
        day = sdate + timedelta(days=i)
        if day not in toRemoveDate: # <-- check if day not in list
            print(day)