英文:
Compare <class 'pandas._libs.tslibs.timestamps.Timestamp'>, str and datetime64[ns] dates in Python
问题
我需要使用各种数据类型的日期进行查询,数据及其相应的数据类型如下所示:
最近的年份和月份: <class 'str'>
** 使用 pd.to_datetime()
并获得 <class 'pandas._libs.tslibs.timestamps.Timestamp'>
格式
当前年份和月份: <class 'str'>
df['Year_Month']: object
查询:
df[(df['Year_Month'] == current_month_year) | (df['Year_Month'] == last_month_year)]
日期包括“年”和“月”,格式为“Year_Month”,例如,`"2020-01"`。
我尝试将它们转换为相同的数据类型,但总会遇到某些问题。将这三种数据类型转换成什么数据类型以进行比较是最好的?谢谢。
英文:
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.
答案1
得分: 0
将'Year_Month'
列和current_month_year
都使用 pd.to_datetime()
方法转换为 datetime64[ns]
类型。
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)]
英文:
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)]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论