Compare <class 'pandas._libs.tslibs.timestamps.Timestamp'>, str and datetime64[ns] dates in Python

Question:

I need to query using dates of various data types, the data and their corresponding data types are listed below:

last_month_year: <class 'str'> ** Used `pd.to_datetime()` and got `<class 'pandas._libs.tslibs.timestamps.Timestamp'>` format
current_month_year: <class 'str'>
df['Year_Month']: object

The query:

df[(df['Year_Month'] == current_month_year) | (df['Year_Month'] == last_month_year)]

The dates consist of "year" and "month" and are of the format "Year_Month", e.g., "2020-01".

I had a few attempts at converting them into the same data type but there are always certain issues. What’s the best data type to convert these three data types into to compare them? Thanks.

Asked By: nilsinelabore

||

Answers:

Convert both 'Year_Month' column and current_month_year to datetime64[ns] type using the pd.to_datetime() method

df['Year_Month'] =  pd.to_datetime(df['Year_Month'])
current_month_year = pd.to_datetime(current_month_year)

out = df[(df['Year_Month'] == current_month_year) | (df['Year_Month'] == last_month_year)]
Answered By: Jamiu S.
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.