Pandas dataframe datetime to time then to seconds

与世无争的帅哥 提交于 2019-11-27 07:24:52

问题


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.


回答1:


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



回答2:


I think you need timedeltas by to_timedelta with times created by split and selecting second lists by str[1], then total_seconds and last cast to 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:

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


来源:https://stackoverflow.com/questions/48129251/pandas-dataframe-datetime-to-time-then-to-seconds

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