pandas 熊猫数据帧日期时间到时间然后到秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48129251/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:01:11  来源:igfitidea点击:

Pandas dataframe datetime to time then to seconds

pythonpython-3.xpandasdatetimepython-datetime

提问by koger23

I have a dataframe. A column contains timestamps. I would like to remove dates and convert the time to seconds.

我有一个数据框。一列包含时间戳。我想删除日期并将时间转换为秒。

First I converted them to datetime:

首先,我将它们转换为日期时间:

In:
df_time = pd.to_datetime(df["Timestamp"])

Out:
0     2017-11-07 13:09:00
1     2017-11-07 13:11:00
2     2017-11-07 13:13:00
3     2017-11-07 13:15:00
dtype: datetime64[ns]

Then I removed dates:

然后我删除了日期:

In:
df_time = pd.Series([val.time() for val in df_time])

Out:
0      13:09:00
1      13:11:00
2      13:13:00
3      13:15:00
4      13:17:00
dtype: object

But they became objects and I did not managed to convert them to datetime-like objects to convert them into seconds. I know there are some similar threads I went trhough them.

但是它们变成了对象,我没有设法将它们转换为类似日期时间的对象以将它们转换为秒。我知道有一些类似的线程我通过它们。

I thank your help in advance.

我提前感谢您的帮助。

回答by Bharath

Since you are converting it to datetime series, simply use basic maths to get the seconds i.e

由于您要将其转换为日期时间序列,因此只需使用基本数学即可获得秒数,即

df_time = pd.to_datetime(df["Timestamp"])

(df_time.dt.hour*60+df_time.dt.minute)*60 + df_time.dt.second

0    47340
1    47460
2    47580
3    47700
Name: Timestamp, dtype: int64

回答by jezrael

I think you need timedeltas by to_timedeltawith timescreated by splitand selecting second lists by str[1], then total_secondsand last cast to int:

我认为你需要timedeltas byto_timedeltatimescreated bysplit并选择第二个lists by str[1],然后total_seconds最后一次投射到int

df_time = pd.to_timedelta(df["Timestamp"].str.split().str[1]).dt.total_seconds().astype(int)
print (df_time)
0    47340
1    47460
2    47580
3    47700
Name: Timestamp, dtype: int32

Detail:

细节:

print (df["Timestamp"].str.split().str[1])
0    13:09:00
1    13:11:00
2    13:13:00
3    13:15:00
Name: Timestamp, dtype: object

print (pd.to_timedelta(df["Timestamp"].str.split().str[1]))
0   13:09:00
1   13:11:00
2   13:13:00
3   13:15:00
Name: Timestamp, dtype: timedelta64[ns]


Or if need seconds form datetimes use dt.second:

或者如果需要秒表datetime使用dt.second

df_time = pd.to_datetime(df["Timestamp"]).dt.second
print (df_time)
0    0
1    0
2    0
3    0
Name: Timestamp, dtype: int64