Python中转换为Datetime类型的问题



我有一个类似于以下内容的Pandas数据帧:

valid               Measurement  Room
2014-02-03 12:48    0.50         23
2014-02-03 12:53    0.43         23
2014-02-03 12:59    0.21         23
2014-02-03 13:06    0.23         23
2014-02-03 13:13    0.10         23
...

我正试着在这些日期阅读。它们当前是字符串,但我想将它们读作date time;然而,结果却不太好。

def hourlyDataSet(fp):
df = pd.read_csv(fp)#data frame
df[['day', 'time']] = df['valid'].str.split().apply(pd.Series)
mat='%Y-%m-%d %H:%M'
df['datetime'] = pd.to_datetime(df['time'],format = mat)
newdf =  df.groupby(pd.Grouper(key = "datetime",freq= "H")).sum()
return df

使用上面的功能,我收到这个错误:

ValueError: time data '12:48' does not match format '%Y-%m-%d%H:%M' (match)

我该怎么解决这个问题?

  • 如果拆分'valid',则mat'time'的格式不匹配
  • 功能应如下
def hourlyDataSet(fp):
# read the data file
df = pd.read_csv(fp)
# convert the valid column, to a datetime format
df['valid'] = pd.to_datetime(df['valid'], format='%Y-%m-%d %H:%M')
# use .Grouper on the datetime column
newdf =  df.groupby(pd.Grouper(key="valid", freq="H")).sum()
return newdf

最新更新