Python 的 ZipInfo.date_time 为什么会把 ZIP 里的奇数秒改成偶数?
用 Python 写入并重新读取 ZIP 条目,核对修改时间里奇数秒的变化。
对比 ZIP 归档前后的修改时间,偶尔可见文件秒数减少 1。借助 ZipInfo.date_time 重新读取归档内容,便能发现该差异源于 ZIP 标准时间字段的精度限制。
ZIP 的秒数按两秒存放
ZipInfo.date_time 从 ZIP 中央目录提取年月日时分秒信息。由于该字段遵循 DOS 时间格式,秒数存储粒度为两秒,奇数秒会被截断至前一个偶数秒。
写入奇数秒和偶数秒
利用 BytesIO 在内存构建 ZIP 对象,分别为两个条目设置 13 秒与 14 秒。结束写入并重新打开归档后,调用 getinfo() 获取时间元组,检查末尾元素以确认秒数。
from io import BytesIO
from zipfile import ZipFile, ZipInfo
buffer = BytesIO()
entries = {"odd.txt": 13, "even.txt": 14}
with ZipFile(buffer, "w") as archive:
for name, seconds in entries.items():
entry = ZipInfo(name, (2026, 12, 6, 10, 20, seconds))
archive.writestr(entry, "sample")
with ZipFile(buffer) as archive:
for name, seconds in entries.items():
stored = archive.getinfo(name).date_time[-1]
print(f"{name}: {seconds} -> {stored}")
预期输出
odd.txt: 13 -> 12
even.txt: 14 -> 14
核对重新读取的结果
写入阶段,13 秒折合 6 个双秒单位,故读回值为 12 秒。14 秒恰好对应 7 个单位,因此读取结果维持 14 秒不变。
保留归档前的准确时间
若备份或审计流程要求精确到秒,建议在归档清单里独立保存源文件修改时间。涉及跨时区比较时,需一并记录时区数据。ZipInfo.date_time 依旧适合用于查阅归档内的标准时间字段。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









