【问题标题】:Passing chopped down datetimes传递切碎的日期时间
【发布时间】:2018-01-17 03:57:13
【问题描述】:

在过去的几个小时里,我一直在试图解决以下问题。

在我从自动化系统获得的大型数据集中,有一个 DATE_TIME 值,对于午夜的行,它的值没有完整的小时,例如:12-MAY-2017 0:16:20

当我尝试将其转换为日期(以便其可用于转换)时,如下所示:

df['DATE_TIME'].astype('datetime64[ns]')

我收到以下错误:

Error parsing datetime string "12-MAY-2017  0:16:20" at position 3

我尝试编写一些正则表达式来提取每个部分,但由于小时可能分别是 1 个或两个字符,因此无法得到任何工作。为每个部分编写正则表达式似乎也不是一个理想的解决方案。

对此有什么想法吗?

【问题讨论】:

    标签: python pandas jupyter-notebook


    【解决方案1】:

    尝试使用pandas.to_datetime()方法:

    df['DATE_TIME'] = pd.to_datetime(df['DATE_TIME'], errors='coerce')
    

    参数errors='coerce' 将处理那些无法转换为datatime dtype 的字符串

    【讨论】:

      【解决方案2】:

      我认为你只需要pandas.to_datetime

      df  = pd.DataFrame({'DATE_TIME':['12-MAY-2017 0:16:20','12-MAY-2017 0:16:20']})
      print (df)
                   DATE_TIME
      0  12-MAY-2017 0:16:20
      1  12-MAY-2017 0:16:20
      
      df['DATE_TIME'] = pd.to_datetime(df['DATE_TIME'])
      print (df)
                  DATE_TIME
      0 2017-05-12 00:16:20
      1 2017-05-12 00:16:20
      

      在 numpy 中转换 astype 似乎是 problematic,因为需要 strings in ISO 8601 date or datetime format

      df['DATE_TIME'].astype('datetime64[ns]')
      

      ValueError:在位置 3 解析日期时间字符串“12-MAY-2017 0:16:20”时出错

      编辑:

      如果日期时间被破坏(某些字符串或整数),则使用MaxU answer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-08
        • 2016-06-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        • 2012-09-14
        相关资源
        最近更新 更多