我需要为遍历文件系统树的 Python 2 程序中的每个文件获取完整的纳秒精度修改时间戳。我想在 Python 本身中执行此操作,因为为每个文件生成一个新的子进程会很慢。
来自 Linux 上的 C 库,you can get nanosecond-precision timestamps通过查看 st_mtime_nsec
领域stat
结果。例如:
#include <sys/stat.h>
#include <stdio.h>
int main() {
struct stat stat_result;
if(!lstat("/", &stat_result)) {
printf("mtime = %lu.%lu\n", stat_result.st_mtim.tv_sec, stat_result.st_mtim.tv_nsec);
} else {
printf("error\n");
return 1;
}
}
打印 mtime = 1380667414.213703287
(/
在 ext4 文件系统上,支持纳秒时间戳,时钟为 UTC)。
同样,date --rfc-3339=ns --reference=/
版画 2013-10-01 22:43:34.213703287+00:00
.
Python (2.7.3) 的 os.path.getmtime(filename)
和 os.lstat(filename).st_mtime
将时间设为 float
.然而,结果是错误的:
In [1]: import os
In [2]: os.path.getmtime('/') % 1
Out[2]: 0.21370339393615723
In [3]: os.lstat('/').st_mtime % 1
Out[3]: 0.21370339393615723
——只有前 6 位数字是正确的,可能是由于 float 错误。
最佳答案
os.stat('/').st_mtime
是一个float对象,对于纳秒级的时间戳,float的精度太低了,
Python’s underlying type for floats is an IEEE 754 double, which is only good for about 16 decimal digits. With ten digits before the decimal point, that leaves six for sub-second resolutions, which is three short of the range required to preserve POSIX nanosecond-resolution timestamps. via: This Week in Python Stupidity: os.stat, os.utime and Sub-Second Timestamps
如果您可以使用 Python 3,则有一个名为 st_mtime_ns
的新属性,它是以纳秒为单位的 st_mtime。试试吧。
>>> os.stat('.').st_mtime
1381571932.044594
>>> os.stat('.').st_mtime_ns
1381571932044593972
引用资料:
PEP 410 -- Use decimal.Decimal type for timestamps
os.stat(): add new fields to get timestamps as Decimal objects with nanosecond resolution
关于python - 获取纳秒级精度的文件修改时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351867/