pythonpandasdatetimedatetime64

Comparison between datetime and datetime64[ns] in pandas


I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it

I'm using:

cur_date = datetime.today()

for today's date. I'm checking if today is in the column with:

bool_val = cur_date in df['date'] #evaluates to false

I do know for a fact that today's date is in the file in question. The dtype of the series is datetime64[ns]

Also, I am only checking the date itself and not the timestamp afterwards, if that matters. I'm doing this to make the timestamp 00:00:00:

cur_date = datetime.strptime(cur_date.strftime('%Y_%m_%d'), '%Y_%m_%d')

And the type of that object after printing is datetime as well


Solution

  • You can use

    pd.Timestamp('today')
    

    or

    pd.to_datetime('today')
    

    But both of those give the date and time for 'now'.


    Try this instead:

    pd.Timestamp('today').floor('D')
    

    or

    pd.to_datetime('today').floor('D')
    

    You could have also passed the datetime object to pandas.to_datetime but I like the other option more.

    pd.to_datetime(datetime.datetime.today()).floor('D')
    

    Pandas also has a Timedelta object

    pd.Timestamp('now').floor('D') + pd.Timedelta(-3, unit='D')
    

    Or you can use the offsets module

    pd.Timestamp('now').floor('D') + pd.offsets.Day(-3)
    

    To check for membership, try one of these

    cur_date in df['date'].tolist()
    

    Or

    df['date'].eq(cur_date).any()