How to resolve error when determining if Date is between two dates

Question:

data = {'Date': ['2022-01-02', '2022-01-13','2022-02-12','2022-02-15']}
df = pd.DataFrame(data) 

I created the Dataframe and then check what the dtype for the new entries are

df['Date']

The dtype shows up as dtype: datetime64[ns]
So now I tried to create dummy variables to determine if something was in between two sets of dates:

df['2/11-2/13  DV']=df['Date'].apply(lambda x: 1 if (2022-02-13 <= x <= 2022-02-13) else 0)

But it keeps return the same error:
TypeError: ‘<=’ not supported between instances of ‘int’ and ‘Timestamp’
Any help on how to resolve this error would be appreciated.

Asked By: James Rush

||

Answers:

Try:

df["2/11-2/13  DV"] = (
    (df["Date"] >= "2022-02-11") & (df["Date"] <= "2022-02-23")
).astype(int)

print(df)

Prints:

         Date  2/11-2/13  DV
0  2022-01-02              0
1  2022-01-13              0
2  2022-02-12              1
3  2022-02-15              1
Answered By: Andrej Kesely
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.