I have an array of dates that should be between 09-2021 and 09-2022. How do I check if every single one of the dates is in the range?
e.g Below are some of the dates within the array
calendar202109['date'].dt.date.unique()
array([datetime.date(2021, 9, 16), datetime.date(2021, 9, 17),
datetime.date(2021, 9, 18), datetime.date(2021, 9, 19),
datetime.date(2022, 9, 15)], dtype=object)
CodePudding user response:
You can use numpy directly for that:
a = array([datetime.date(2021, 9, 16), datetime.date(2021, 9, 17),
datetime.date(2021, 9, 18), datetime.date(2021, 9, 19),
datetime.date(2022, 9, 15)], dtype=object)
((a > pd.Timestamp('2021-09-01')) & (a < pd.Timestamp('2022-08-31'))).all()
output: False
To identify the outliers:
m = ((a > datetime.date(2021, 9, 1)) & (a < pd.Timestamp('2022-08-31')))
a[~m]
output: array([datetime.date(2022, 9, 15)], dtype=object)
NB. using here pd.Timestamp('2021-09-01')
as a convenience, you can use datetime.date(2021, 9, 1)
instead.
CodePudding user response:
Without the aid of pandas you could just do this:
from datetime import date
list_ = [date(2021, 9, 16),
date(2021, 9, 17),
date(2021, 9, 18),
date(2021, 9, 19),
date(2022, 9, 15)]
lo_bound = date(2021, 9, 1)
hi_bound = date(2022, 8, 31)
for d in list_:
if not lo_bound <= d <= hi_bound:
print(d, 'Out of range')
Output:
2022-09-15 Out of range