Compare Dates in Column Headers

65 Views Asked by At

Currently my column headers are in the format x.strftime('%b %Y') (Eg. June 2022, Jul 2022, Aug 2022 and so on....)

I want to apply the following code selecting a particular range of cols with the below code:

Df = Df.loc[:, (Df.columns >= datetime.date(2022, 2, 1)) & (Df.columns <= datetime.date(2023, 2, 28))]

However, I am getting the following error:

'>=' not supported between instances of 'str' and 'datetime.date'

How can I compare the two?

1

There are 1 best solutions below

0
Jamiu S. On

You first need to convert dates from str to datetime objects using pd.to_datetime() and then in Df.lo[] you convert the dates range to Timestamp objects using pd.Timestamp()

Df.columns = pd.to_datetime(Df.columns, format="%b %Y")

Df = Df.loc[:, (Df.columns >= pd.Timestamp(datetime.date(2022, 2, 1))) & 
            (Df.columns <= pd.Timestamp(datetime.date(2023, 2, 28)))]