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

huangapple go评论60阅读模式
英文:

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: &lt;class &#39;str&#39;&gt; ** Used `pd.to_datetime()` and got `&lt;class &#39;pandas._libs.tslibs.timestamps.Timestamp&#39;&gt;` format
current_month_year: &lt;class &#39;str&#39;&gt;
df[&#39;Year_Month&#39;]: object

The query:

df[(df[&#39;Year_Month&#39;] == current_month_year) | (df[&#39;Year_Month&#39;] == last_month_year)]

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

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 &#39;Year_Month&#39; column and current_month_year to datetime64[ns] type using the pd.to_datetime() method

df[&#39;Year_Month&#39;] =  pd.to_datetime(df[&#39;Year_Month&#39;])
current_month_year = pd.to_datetime(current_month_year)

out = df[(df[&#39;Year_Month&#39;] == current_month_year) | (df[&#39;Year_Month&#39;] == last_month_year)]

huangapple
  • 本文由 发表于 2023年2月6日 13:30:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定