Pandas 数据帧日期时间到时间然后到秒

Pandas dataframe datetime to time then to seconds

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

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

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]

然后我删除了日期:

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

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

在此先感谢您的帮助。

我认为你需要 to_timedelta with times created by split and selecting second lists by str[1], then total_secondstimedeltas,最后投射到 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

详情:

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]

或者如果需要秒表 datetimes 使用 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

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

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

如果您要减去持续时间,请使用下面的内容以秒为单位进行转换 (tsession['EndTime'] -tsession['StartTime'])/ np.timedelta64(1, 's')