使用python从时间戳中提取小时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39370879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
extract hour from timestamp with python
提问by Poisson
I have a dataframe df_energy2
我有一个数据框 df_energy2
df_energy2.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 29974 entries, 0 to 29973
Data columns (total 4 columns):
TIMESTAMP 29974 non-null datetime64[ns]
P_ACT_KW 29974 non-null int64
PERIODE_TARIF 29974 non-null object
P_SOUSCR 29974 non-null int64
dtypes: datetime64[ns](1), int64(2), object(1)
memory usage: 936.8+ KB
with this structure :
使用这种结构:
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
Is there any python fucntion which can extract hour from TIMESTAMP
?
是否有任何可以从中提取小时的 python 功能TIMESTAMP
?
Kind regards
亲切的问候
采纳答案by jezrael
回答by 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
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
:
编辑:是的,jezrael 你是对的。放上他所说的:pandas 数据框有一个属性,即dt
:
<dataframe>.<ts_column>.dt.hour
Example in your context - the column with date is TIMESTAMP
您的上下文中的示例 - 带有日期的列是 TIMESTAMP
df.TIMESTAMP.dt.hour
A similar question - Pandas, dataframe with a datetime64 column, querying by hour
一个类似的问题 - Pandas,带有 datetime64 列的数据框,按小时查询