Split dataframe on the basis of date

Viewed 9907

I am trying to split a dataframe into two based on date. This has been solved for a related problem here: Split dataframe into two on the basis of date

My dataframe looks like this:

               abcde     col_b
2008-04-10  0.041913  0.227050
2008-04-11  0.041372  0.228116
2008-04-12  0.040835  0.229199
2008-04-13  0.040300  0.230301
2008-04-14  0.039770  0.231421

How do I split it based on date (say before 2008-04-12 and after)? When I try this:

df.loc[pd.to_datetime(df.index) <= split_date]

where split_date is datetime.date(2008-04-12), I get this error:

*** TypeError: <class 'datetime.date'> type object 2008-04-12
3 Answers

For reference, if you are looking to get the dataframe between two dates you can do this following @R.A.Munna's logic:

import datetime

split_date_one = datetime.date(2019,9,26)
split_date_two = datetime.date(2019,10,13)

df= df[(pd.to_datetime(df[df.columns[0]]) >= split_date_one) & (pd.to_datetime(df[df.columns[0]]) <= split_date_two)]
Related