extract hour from timestamp with python

瘦欲@ 提交于 2019-12-01 03:54:10

I think you need dt.hour:

print (df.TIMESTAMP.dt.hour)
0    0
1    0
Name: TIMESTAMP, dtype: int64

df['hours'] = df.TIMESTAMP.dt.hour
print (df)
            TIMESTAMP  P_ACT_KW PERIODE_TARIF  P_SOUSCR  hours
0 2016-01-01 00:00:00       116            HC       250      0
1 2016-01-01 00:10:00       121            HC       250      0
Nabeel Ahmed

Given your data:

df_energy2.head()

TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR
2016-01-01 00:00:00 116 HC 250 
2016-01-01 00:10:00 121 HC 250

You have timestamp as the index. For extracting hours from timestamp where you have it as the index of the dataframe:

  hours = df_energy2.index.hour

Edit: Yes, jezrael you're right. Putting what he has stated: pandas dataframe has a property for this i.e. dt :

<dataframe>.<ts_column>.dt.hour

Example in your context - the column with date is TIMESTAMP

df.TIMESTAMP.dt.hour

A similar question - Pandas, dataframe with a datetime64 column, querying by hour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!