【问题标题】:Python/Pandas: How do I convert from datetime64[ns] to datetimePython/Pandas:如何从 datetime64[ns] 转换为 datetime
【发布时间】:2017-01-05 13:36:12
【问题描述】:

我有一个处理 Excel 文件的脚本。发送它的部门有一个生成它的系统,我的脚本停止工作。

我突然收到以下代码行的错误Can only use .str accessor with string values, which use np.object_ dtype in pandas

df['DATE'] = df['Date'].str.replace(r'[^a-zA-Z0-9\._/-]', '')

我检查了旧系统文件中日期列的类型 (dtype: object) 与新系统文件 (dtype: datetime64[ns])。

如何将日期格式更改为我的脚本可以理解的格式?

我看到了this answer,但我对日期格式的了解并不那么细致。

【问题讨论】:

  • 您可以使用df['Date'].dt.strftime('%Y-%m-%d') 将日期转换回字符串。
  • 成功了,谢谢。

标签: python-2.7 datetime pandas datetime64


【解决方案1】:

您可以在数据框列上使用apply 函数将必要的列转换为字符串。例如:

df['DATE'] = df['Date'].apply(lambda x: x.strftime('%Y-%m-%d'))

确保导入datetime 模块。

apply() 将一次对每个单元格进行评估,并应用lambda 函数中指定的格式。

【讨论】:

    【解决方案2】:

    pd.to_datetime 返回一系列datetime64 dtype,如下所述:

    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

    df['DATE'] = df['Date'].dt.date
    

    或者这个:

    df['Date'].map(datetime.datetime.date) 
    

    【讨论】:

      【解决方案3】:

      您可以使用pd.to_datetime

      df['DATE'] = pd.to_datetime(df['DATE'])
      

      【讨论】:

      • 我不知道为什么这个答案被接受,因为我相信它保持类型 datetime64[ns]
      猜你喜欢
      • 2020-11-05
      • 2019-03-29
      • 1970-01-01
      • 2020-04-28
      • 2019-01-20
      • 1970-01-01
      • 2022-08-15
      • 2021-09-27
      • 2015-11-02
      相关资源
      最近更新 更多