我通过命令行从数据帧的时间戳中提取了几个小时:
import pandas as pd
from datetime import *
from datetime import datetime
import datetime as dt
import time
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['time'] = df['timestamp'].dt.time
df['time']
Output: id time
3539 23:49:58
3540 23:52:39
3541 23:55:19
3542 23:58:00
Name: time, dtype: object
我需要将时间列转换为秒,即 23:49:58 = 23 * 3600 + 49 * 60 + 58 = 85798秒
id time
3539 85798
非常感谢
答案 0 :(得分:1)
将日期时间转换为hour
s,minute
和second
s:
df['time'] = df['timestamp'].dt.hour * 3600 +
df['timestamp'].dt.minute * 60 +
df['timestamp'].dt.second
或to_timedelta
并获取total_seconds
:
df['time'] = pd.to_timedelta(df['timestamp'].dt.strftime('%H:%M:%S'))
.dt.total_seconds().astype(int)
<强>示例强>:
df = pd.DataFrame({'timestamp':['2015-04-01 23:49:58','2016-04-01 23:49:58']})
df['timestamp'] = pd.to_datetime(df['timestamp'])
print (df)
timestamp
0 2015-04-01 23:49:58
1 2016-04-01 23:49:58
df['time1'] = df['timestamp'].dt.hour * 3600 + \
df['timestamp'].dt.minute * 60 + \
df['timestamp'].dt.second
df['time2'] = (pd.to_timedelta(df['timestamp'].dt.strftime('%H:%M:%S'))
.dt.total_seconds().astype(int))
print (df)
timestamp time1 time2
0 2015-04-01 23:49:58 85798 85798
1 2016-04-01 23:49:58 85798 85798