首页 > 解决方案 > 时间戳字符串到数据帧中的秒数

问题描述

我有一个包含时间戳列的大型数据框,如下所示:

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))

标签: pythonpandasdataframedatetime

解决方案


您可以用 解析字符串strptime,减去start_timeas 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')

推荐阅读