【问题标题】:Convert the column '6/25/2019 10:06:49 AM' to date type from object type in pandas将“6/25/2019 10:06:49 AM”列从 pandas 中的对象类型转换为日期类型
【发布时间】:2019-11-07 08:41:16
【问题描述】:

我需要将此 '6/25/2019 10:06:49 AM' 转换为实际为对象类型的日期数据类型。

df["TIME"] = pd.to_datetime(df["TIME"], format='%m/%d/%Y %I:%M:%S %p')

我尝试过使用它,但它会引发以下错误。

AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandas

【问题讨论】:

    标签: pandas


    【解决方案1】:

    注意:在将其转换为日期格式之前,您需要删除列中的多余空格。

    删除多余的空格:

    df.TIME = df.TIME.str.rstrip()
    

    现在尝试使用以下代码转换为日期数据类型:

    df["TIME"] = pd.to_datetime(df["TIME"])
    (or)
    df["TIME"] = pd.to_datetime(df["TIME"], format='%m/%d/%Y %I:%M:%S %p')
    

    注意:%H 用于 24 小时,%I 用于 12 小时。

    【讨论】:

      猜你喜欢
      • 2017-09-29
      • 2022-01-06
      • 1970-01-01
      • 2021-04-29
      • 2018-06-25
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多