python - 时间戳字符串到数据帧中的秒数
问题描述
我有一个包含时间戳列的大型数据框,如下所示:
Timestamp
16T122109960
16T122109965
16T122109970
16T122109975
[73853 rows x 1 columns]
我需要将其转换为自第一个时间戳列以来的秒数(格式为 12.523),使用如下所示:
start_time = log_file['Timestamp'][0]
log_file['Timestamp'] = log_file.Timestamp.apply(lambda x: x - start_time)
但首先我需要尽快将时间戳解析为秒,我尝试使用正则表达式将时间戳拆分为小时、分钟、秒和毫秒,然后适当地进行乘法和除法,但出现内存错误。datetime 或 dateutils 中是否有可以提供帮助的函数?
我目前使用的方法如下:
def regex_time(time):
list = re.split(r"(\d*)(T)(\d{2})(\d{2})(\d{2})(\d{3})", time)
date, delim, hours, minutes, seconds, mills = list[1:-1]
seconds = int(seconds)
seconds += int(mills) /1000
seconds += int(minutes) * 60
seconds += int(hours) * 3600
return seconds
df['Timestamp'] = df.Timestamp.apply(lambda j: regex_time(j))
解决方案
您可以用 解析字符串strptime
,减去start_time
as apd.Timestamp
并使用total_seconds()
结果timedelta
:
import pandas as pd
df = pd.DataFrame({'Timestamp': ['16T122109960','16T122109965','16T122109970','16T122109975']})
start_time = pd.Timestamp('1900-01-01')
df['totalseconds'] = (pd.to_datetime(df['Timestamp'], format='%dT%H%M%S%f')-start_time).dt.total_seconds()
df['totalseconds']
# 0 1340469.960
# 1 1340469.965
# 2 1340469.970
# 3 1340469.975
# Name: totalseconds, dtype: float64
要将“时间戳”列的第一个条目用作参考时间start_time
,请使用
start_time = pd.to_datetime(df['Timestamp'].iloc[0], format='%dT%H%M%S%f')
推荐阅读
- r - 在 R 中使用 AND 和 OR 布尔运算符检测字符串
- database - 表 DDL 元数据的最后修改时间
- php - 使用 xpath 获取元素的最小/最大值
- java - Spring-Boot:错误注入多个bean
- ms-access - System.Data.Odbc.OdbcException (0x80131937) 发布后,我无法使用 Odbc 功能读取、删除和写入访问 mdb 文件
- java - 使用 LWJGL opengl 对球体进行纹理处理?
- java - 使用 AlarmManager 和 BroadcastReciver 创建警报
- c# - 如何检查 2 个触发器是否会发生冲突?
- powershell - 流水线 Powershell cmdlet 显示部分结果?
- python - 遍历字典 即时更新值 Python3