Viktor.w
Viktor.w

Reputation: 2317

Compare timestamp with datetime

I have one timestamp from a dataframe and a datetime object, I want to compare them to do a select in a dataframe. My data are as followed:

print(type(datetime.datetime.now()))
<class 'datetime.datetime'>

print(type((df.created_at[0])))
<class 'pandas._libs.tslibs.timestamps.Timestamp'>

How can I select specific rows within that dataframe with the datetime object? as follow:

df[df.created > datetime.datetime.now()]

But it returns me the following error message: TypeError: Cannot compare tz-naive and tz-aware datetime-like objects, any idea on how to solve that? thanks!

Upvotes: 1

Views: 5095

Answers (2)

Ludi
Ludi

Reputation: 463

df[df.created.to_pydatetime() > datetime.datetime.now()]

Should work pandas.Timestamp.to_pydatetime

Upvotes: 0

Always Right Never Left
Always Right Never Left

Reputation: 1481

Timestamp is a timezone-aware object, while the datetime object you get from datetime.datetime.now() is timezone-naive since you don't specify otherwise, hence the error. You should convert so that they're either both timezone-aware or both timezone-naive.

For example, you can call datetime.datetime.now() like this to make it timezone-aware (passing timezone info from timestamp object as an argument):

datetime.datetime.now(df.created_at[0].tzinfo)

Upvotes: 2

Related Questions