'Zipfile lib weird behaviour with seconds in modified time
Working with zipfile module I found something weird about how it works.
I'm zipping one file, which last modified attr time is: 13:40:31 (HH:MM:SS) When I zip and unzip the file, its last mod time is 13:40:30 (lost 1 second)
Doing some tests around this, I used ZipInfo object to manually set the last modified time to 13:40:31 but still get 13:40:30.
I also tried setting to 13:40:41 and then I got 13:40:40.
Trying any other value to seconds, it works fine, so if I set it to 13:40:32, it's ok when unzip the file.
Any clue about this? Am I missing something?
OS: Windows 10 (64 bits) Python: 3.7
Test Just compress any file and then unzip it and compare last modified time
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()
Solution 1:[1]
By default zip file store timestamps to a 2 second accuracy. This dates waaay back in time to when DOS ruled the world and every bit counted. Below is the definition of how it works from the ZIp spec (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.
Although that default legacy is still present in modern zip files, most zip implementations also use an extended attribute to store the timestamp accurately.
Looks like Python doesn't support that feature.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | pmqs |