Comparison between datetime and datetime64[ns] in pandas

Question:

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

Asked By: JesusMonroe

||

Answers:

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 mroe.

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()
Answered By: piRSquared

For anyone who also stumbled across this when comparing a dataframe date to a variable date, and this did not exactly answer your question; you can use the code below.

Instead of:

self.df["date"] = pd.to_datetime(self.df["date"])

You can import datetime and then add .dt.date to the end like:

self.df["date"] = pd.to_datetime(self.df["date"]).dt.date
Answered By: Tobias Funke

When converting datetime64 type using pd.Timestamp() it is important to note that you should compare it to another timestamp type. (not a datetime.date type)


Convert a date to numpy.datetime64

date = '2022-11-20 00:00:00'
date64 = np.datetime64(date)

Seven days ago – timestamp type

sevenDaysAgoTs = (pd.to_datetime('today')-timedelta(days=7))

convert date64 to Timestamp and see if it was in the last 7 days

print(pd.Timestamp(pd.to_datetime(date64)) >= sevenDaysAgoTs)

Answered By: JerryMcDonald.dev
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.