pandas - 使用 pandas 将小时转换为秒

标签 pandas time-series

我通过命令行从数据帧的时间戳中提取了几个小时:

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/

相关文章:

r - 使用 R 的 SARIMAX 模型的数值方法

python - 通过将函数应用于 pandas Series 来获取字典

python - Pandas:标记另一列标志之间的值

python-3.x - 在文本列上使用 Pandas 滚动功能

python - 将 PySpark 数据框重新采样从几个月到几周

python - 在Python中忽略大于x分钟的时间间隔Matplotlib

python - 使用 matplotlib 在线图/时间序列上的多条线

python - 安装 Pandas : UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 72: ordinal not in range(128)

python - Numpy - 将第一行作为名称立即加载到结构化数组中?

r - 计算一段时间内的返回