我通过命令行从数据帧的时间戳中提取了几个小时:
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
非常感谢
最佳答案
将日期时间转换为小时
、分钟
和秒
:
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
关于pandas - 使用 pandas 将小时转换为秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48787670/