Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - Pandas dataframe datetime to time then to seconds

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...