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

如何使用PyShark从PCAP帧中提取UNIX时间戳?

解决PyShark获取PCAP数据包UNIX时间戳的问题

其实PyShark并没有遗漏这个功能,时间戳信息不在IP/UDP/RTP这些协议层数据里,而是存于数据包的底层捕获属性中,你可以通过以下方式直接获取:

方法1:获取UNIX时间戳(毫秒级精度)

访问packet.sniff_timestamp属性即可得到自1970年以来的UNIX时间戳(浮点数格式),示例代码:

import pyshark

cap = pyshark.FileCapture('your_capture.pcap')
for packet in cap:
    unix_timestamp = float(packet.sniff_timestamp)
    print(f"数据包UNIX时间戳:{unix_timestamp}")
cap.close()

方法2:获取更多时间相关元数据

如果需要更灵活的时间格式或拆分信息,还可以使用这些属性:

  • packet.sniff_time:返回Python原生datetime对象,直接对应可读的捕获时间
  • packet.sniff_epoch:与sniff_timestamp功能一致,返回UNIX时间戳浮点数
  • packet.sniff_usec:单独返回捕获时间的微秒部分

示例代码:

for packet in cap:
    # 输出可读格式时间
    print(f"捕获时间:{packet.sniff_time}")
    # 拆分秒与微秒
    ts_sec = int(packet.sniff_timestamp)
    ts_usec = int((packet.sniff_timestamp - ts_sec) * 1000000)
    print(f"秒数:{ts_sec},微秒数:{ts_usec}")

为什么str(packet)看不到时间戳?

str(packet)默认仅打印协议层的解析内容,不会展示底层的捕获元数据。你可以通过打印packet.__dict__查看数据包的所有属性,就能找到这些时间相关字段。

内容的提问来源于stack exchange,提问作者edward hiskes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:55:37