'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 1:[1]
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)
Solution 2:[2]
Try .drop()
from datetime import timedelta, date
import pandas as pd
sdate = date(2020, 7, 1)
edate = date(2020, 7, 7)
range = pd.date_range(start=str(sdate), end=str(edate))
toRemoveDate = [date(2020, 7, 6), date(2020, 7, 2)]
days = range.drop(toRemoveDate)
print(days)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sushanth |
| Solution 2 | Kyuubi |
