【问题标题】:Convert pandas column of date and datetime to date将日期和日期时间的熊猫列转换为日期
【发布时间】:2020-06-19 09:11:34
【问题描述】:

我有一列可能同时包含日期和日期时间对象,我想将它们全部转换为日期。

如果我这样做df['DT_REFERENCE'].dt.date,它将在日期上抛出错误。

我能想到的最佳解决方案是

df['DT_REFERENCE'].astype('datetime64[ns]').dt.date

但我想知道是否有更好的方法。

【问题讨论】:

  • df['DT_REFERENCE'] 的 dtype 是什么?请注意,pandas 中只有 datetime,即输入中是否只有时间或日期无关紧要 - 将添加默认值。如果您使用.dt.date 将日期时间列转换为“仅限日期”,则结果将是 dtype 字符串(对象)。

标签: python pandas date datetime


【解决方案1】:

使用to_datetime:

pd.to_datetime(df['DT_REFERENCE']).dt.date

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 2021-12-06
    • 2017-05-20
    • 2017-08-24
    • 1970-01-01
    • 2021-09-16
    相关资源
    最近更新 更多