【问题标题】:Pandas "object" series doesn't convert to datetime, I need just the hour [duplicate]熊猫“对象”系列不会转换为日期时间,我只需要小时 [重复]
【发布时间】:2021-10-29 07:37:24
【问题描述】:

我只需要 df 列中的一个小时,如下所示:

2021-04-30 09:32 +0000

所以我把它分开了:

#split the time column into hour and date
df_new['date'] = df_new['time'].astype(str)
# split date into 3 columns
df_new[['date_1','hour','remove']] = df_new['date'].astype(str).str.split(expand=True)
#drop unnecessary columns
df_new = df_new.drop(labels=['time','date','remove'], axis=1)
from datetime import datetime
df_new['hour']= df_new['hour'].astype(str)
#format hour column as date time
df_new['hour'] = pd.to_datetime(df_new['hour'], format='%H:%M').dt.time

结果是:

0     09:32:00
1     01:00:00
2     17:18:00
3     13:08:00
4     11:26:00

但我只需要几个小时,而且我总是得到与它不是日期时间格式相同的错误,因为列 dtypeobject。我尝试了所有解决方案,但没有奏效。

【问题讨论】:

  • 如果您从.csv 文件创建dataframe 对象,则可以在pandas.read_csv() 方法中使用parse_dates 参数,然后您可以使用dt 访问器来提取@987654331 @来自date 列中的每个日期时间对象,即df_new['hour'] = df_new['date'].dt.hour

标签: python pandas dataframe datetime


【解决方案1】:

将您的列转换为日期时间并使用.dt.hour

pd.to_datetime(df['date']).dt.hour

【讨论】:

    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 2015-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    相关资源
    最近更新 更多