1

使用 zipfile 模块时,我发现它的工作原理有些奇怪。

我正在压缩一个文件,最后修改时间是:13:40:31 (HH:MM:SS) 当我压缩和解压缩文件时,它的最后修改时间是 13:40:30(丢失 1 秒)

围绕这个做一些测试,我使用 ZipInfo 对象手动将上次修改时间设置为 13:40:31,但仍然得到 13:40:30。

我还尝试设置为 13:40:41,然后我得到了 13:40:40。

尝试将任何其他值设置为秒,它工作正常,所以如果我将其设置为 13:40:32,解压缩文件时就可以了。

对此有任何线索吗?我错过了什么吗?

操作系统:Windows 10(64 位)Python:3.7

测试只需压缩任何文件然后解压缩并比较上次修改时间

file = 'testfile.txt'

zf = zipfile.ZipFile(file='test.zip', mode='w', compression=zipfile.ZIP_DEFLATED)

info = zipfile.ZipInfo(file, 
    date_time=(2020, 9, 23, 13, 40, 31))

zf.writestr(info, open(file, 'r').read(), zipfile.ZIP_DEFLATED, 6)
zf.close()

提前致谢!

4

1 回答 1

1

默认情况下,zip 文件存储时间戳的精度为 2 秒。这可以追溯到 DOS 统治世界并且每一点都很重要的时候。以下是 ZIp 规范 ( APPNOTE.TXT )中它如何工作的定义

   4.4.6 date and time fields: (2 bytes each)
 
       The date and time are encoded in standard MS-DOS format.
       If input came from standard input, the date and time are
       those at which compression was started for this data. 
       If encrypting the central directory and general purpose bit 
       flag 13 is set indicating masking, the value stored in the 
       Local Header will be zero. MS-DOS time format is different
       from more commonly used computer time formats such as 
       UTC. For example, MS-DOS uses year values relative to 1980
       and 2 second precision.

  尽管现代 zip 文件中仍然存在该默认遗留文件,但大多数 zip 实现还使用扩展属性来准确存储时间戳。

看起来 Python 不支持该功能。

于 2020-09-24T16:12:21.313 回答