【问题标题】:Compare <class 'pandas._libs.tslibs.timestamps.Timestamp'>, str and datetime64[ns] dates in Python在 Python 中比较 <class \'pandas._libs.tslibs.timestamps.Timestamp\'>、str 和 datetime64[ns] 日期
【发布时间】:2023-02-07 06:53:51
【问题描述】:

我需要使用各种数据类型的日期进行查询,数据及其对应的数据类型如下:

last_month_year: <class 'pandas._libs.tslibs.timestamps.Timestamp'>
current_month_year: <class 'str'>
df['Year_Month']: datetime64[ns]

查询:

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

日期由“年”和“月”组成,格式为“年_月”,例如"2020-01"

我尝试过几次将它们转换为相同的数据类型,但总是存在某些问题。将这三种数据类型转换成什么数据类型比较好?谢谢。

【问题讨论】:

  • Year_Month系列的数据类型是什么?是str吗? last_month_year是怎么计算出来的?

标签: python pandas date


【解决方案1】:

使用pd.to_datetime()方法将'Year_Month'列和current_month_year转换为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)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2019-01-20
    • 2020-09-04
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多