Zipfile lib奇怪的行为,修改后的时间为秒

问题描述

使用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()

谢谢!

解决方法

默认情况下,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不支持该功能。