【问题标题】:pd.to_datetime Hours and Secondspd.to_datetime 小时和秒
【发布时间】:2018-07-04 18:58:30
【问题描述】:

晚上好,

我有一个数据框(Pandas),其中有一列代表日期,格式如下:

print(df["date"])

14/01/18 12:47
14/01/18 12:48
14/01/18 12:50
14/01/18 12:57
14/01/18 12:57
14/01/18 12:57
14/01/18 12:57
14/01/18 12:57
14/01/18 12:58

具体来说,我想: 1. 使用pd.to_datetime转换它为datetime 2. 创建以下附加

df["month"]
df["day"]
df["year"]
df["hour"]
df["minute"]

我试着跑了:

df['date'] = pd.to_datetime(df['date'], format = "%d/%m/%Y %H/%M" )

但出现以下错误

time data '02/01/18 08:41' does not match format '%d/%m/%Y %H/%M' (match)

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    你可以像下面这样在 format= 之间输入冒号(:)

    df['Date/Time']=pd.to_datetime(df['Date/Time'],format='%m/%d/%Y %H:%M:%S')
    

    【讨论】:

      【解决方案2】:

      替代grovina的答案......您可以直接使用dt访问器而不是使用apply。

      这是一个示例:

      >>> data = [['2017-12-01'], ['2017-12-30'],['2018-01-01']]
      >>> df = pd.DataFrame(data=data, columns=['date'])
      >>> df
               date
      0  2017-12-01
      1  2017-12-30
      2  2018-01-01
      >>> df.date
      0    2017-12-01
      1    2017-12-30
      2    2018-01-01
      Name: date, dtype: object
      

      注意 df.date 是一个对象吗?让我们把它变成你想要的日期

      >>> df.date = pd.to_datetime(df.date)
      >>> df.date
      0   2017-12-01
      1   2017-12-30
      2   2018-01-01
      Name: date, dtype: datetime64[ns]
      

      您想要的格式是字符串格式。我认为您无法将实际的 datetime64 转换为该格式。现在,让我们在单独的列中创建一个新格式化的日期字符串版本

       >>> df['new_formatted_date'] = df.date.dt.strftime('%d/%m/%y %H:%M')
       >>> df.new_formatted_date
       0    01/12/17 00:00
       1    30/12/17 00:00
       2    01/01/18 00:00
       Name: new_formatted_date, dtype: object
      

      最后,由于 df.date 列现在的日期为 datetime64... 您可以在其上使用 dt 访问器。无需使用apply

      >>> df['month'] = df.date.dt.month
      >>> df['day'] = df.date.dt.day
      >>> df['year'] = df.date.dt.year
      >>> df['hour'] = df.date.dt.hour
      >>> df['minute'] = df.date.dt.minute
      >>> df
              date new_formatted_date  month  day  year  hour  minute
      0 2017-12-01     01/12/17 00:00     12    1  2017     0       0
      1 2017-12-30     30/12/17 00:00     12   30  2017     0       0
      2 2018-01-01     01/01/18 00:00      1    1  2018     0       0
      

      【讨论】:

        【解决方案3】:

        您想要的格式'%d/%m/%y %H:%M'(小时和分钟之间的小写y和冒号)。看看here

        然后你可以创建其他列:

        df['month'] = df['date'].apply(lambda x: x.month)
        df['day'] = df['date'].apply(lambda x: x.day)
        df['year'] = df['date'].apply(lambda x: x.year)
        df['hour'] = df['date'].apply(lambda x: x.hour)
        df['minute'] = df['date'].apply(lambda x: x.minute)
        

        【讨论】:

        • 这比使用 df.date.dt.month 访问器的 df.date.dt.month 方法要慢
        猜你喜欢
        • 2012-06-08
        • 1970-01-01
        • 2015-06-02
        • 1970-01-01
        • 2013-01-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多