user16996079
user16996079

Reputation:

Finding datetime object in pandas df column

I have the following code, where I want to determine if a datetime object exists in a data frame.

Here is the code:

df_grid['Date'] = pd.to_datetime(df_grid['Date'])
start_date = df_grid['Date'].iloc[0].date() 
end_date = df_grid['Date'].iloc[-1].date()
current_date = start_date

while current_date < end_date:
    current_date += datetime.timedelta(days=1)
    print(current_date)
    if current_date in df_grid['Date']: continue
    print('not in')

And here is what the dataframe column looks like:

Date
2021-11-01
2021-11-01
2021-11-01
2021-11-02
2021-11-02
2021-11-03
2021-11-03
...

Most of the dates do exist in the column; however, when I run the code, it indicates that none of the dates exist in the dataframe column. I've tried matching with and without .date() and get the same results.

Upvotes: 0

Views: 466

Answers (1)

user16996079
user16996079

Reputation:

Well, this is what I ended up doing to identify missing dates in the dateframe

    while current_date < end_date:
        missing = True
        for row in df_grid.index:
            if current_date == df_grid['Date'].iloc[row]:
                missing = False
                break
        if missing == True:
            [code to execute when date is missing]
        current_date += datetime.timedelta(days=1)

Seems a lot more inefficient than what I originally tried to do, but at least this works.

Upvotes: 1

Related Questions