You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python将Wireshark格式时间转为Unix纪元秒数

Python将Wireshark时间格式转换为Unix纪元秒数

核心思路

Wireshark的时间格式是YYYY-MM-DD HH:MM:SS.ffffff(包含6位微秒),我们可以用Python的datetime模块解析该格式,再直接转换为带微秒的Unix纪元秒数(从1970-01-01 00:00:00 UTC开始的累计秒数)。

完整代码示例

假设你的时间数据每行一个,存储在timestamps.txt文件中:

from datetime import datetime

def convert_wireshark_to_unix(time_str):
    # 严格匹配Wireshark时间格式,%f对应6位微秒
    dt_obj = datetime.strptime(time_str.strip(), "%Y-%m-%d %H:%M:%S.%f")
    # 转换为带微秒的Unix时间戳
    return dt_obj.timestamp()

# 读取文件并批量处理
with open("timestamps.txt", "r", encoding="utf-8") as in_file:
    # 可选:创建输出文件保存结果
    with open("unix_timestamps.txt", "a", encoding="utf-8") as out_file:
        for line in in_file:
            cleaned_line = line.strip()
            if not cleaned_line:
                continue
            try:
                unix_time = convert_wireshark_to_unix(cleaned_line)
                print(unix_time)
                out_file.write(f"{unix_time}\n")
            except ValueError:
                print(f"跳过无效时间格式: {cleaned_line}")

关键细节

  • strptime的格式字符串%Y-%m-%d %H:%M:%S.%f完全对应Wireshark的时间结构,确保微秒部分被正确解析。
  • timestamp()方法直接返回浮点型结果,和你给出的示例格式(如1671971890.8821542)完全一致。
  • 加入了空行跳过和异常捕获逻辑,避免因文件中存在无效内容导致程序崩溃。

内容的提问来源于stack exchange,提问作者wawo lala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 06:05:31