【发布时间】:2021-12-31 06:26:43
【问题描述】:
以下测试总是失败(这在 linux 系统上运行,问题与其他操作系统无关):
from time import time
from decimal import Decimal
from pathlib import Path
def test_timing():
start = Decimal(time())
p = Path(__file__).parent / 'testfile.txt' # does not yet exist
p.touch()
mt = p.stat().st_mtime
p.unlink() # unlinked before the failing assert
> assert start <= mt
E AssertionError: assert Decimal('1640930671.75709438323974609375') <= 1640930671.7534654
间隔总是大约 3 到 7 毫秒。
Decimal(time()) 在开始时返回的时间戳怎么可能比在它之后两行创建的文件晚?
python 时间戳和 linux 时间戳之间是否存在偏移? python 是否在Decimal(time()) 调用完成之前继续创建文件?我在这里错过了什么?
编辑:我应该提到它是 ext4 文件系统。
【问题讨论】:
-
文件系统不会以无限精度存储时间戳;原来的 FAT 文件系统有 2 秒 的粒度!显然,您正在使用的时间戳至少有时会四舍五入到下一个可表示的时间戳。
-
不是这样的。 ext4 将时间戳存储到纳秒。我会发布真正的答案。
标签: python python-3.x linux ext4 filemtime