使文件修改时间达到纳秒级精度 [英] Get file modification time to nanosecond precision
问题描述
我需要获取遍历文件系统树的Python 2程序中每个文件的完整纳秒精度修改时间戳.我想在Python本身中执行此操作,因为为每个文件生成一个新的子进程会很慢.
I need to get the full nanosecond-precision modified timestamp for each file in a Python 2 program that walks the filesystem tree. I want to do this in Python itself, because spawning a new subprocess for every file will be slow.
在Linux上的C库中,您可以通过查看stat
结果的st_mtime_nsec
字段来获得纳秒级的时间戳.例如:
From the C library on Linux, you can get nanosecond-precision timestamps by looking at the st_mtime_nsec
field of a stat
result. For example:
#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).
prints mtime = 1380667414.213703287
(/
is on an ext4 filesystem, which supports nanosecond timestamps, and the clock is 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
给出mtime作为float
.但是,结果是错误的:
Python (2.7.3)'s os.path.getmtime(filename)
and os.lstat(filename).st_mtime
give the mtime as a float
. However, the result is wrong:
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位数字是正确的,大概是由于浮点错误引起的.
—only the first 6 digits are correct, presumably due to floating-point error.
推荐答案
或者,您也可以使用 cffi 与以下代码一起在Python 2中使用的库(<在LInux上测试 ):
Alternatively you coudl use the cffi library which works with Python 2 with the follwoing code (tested on LInux):
from __future__ import print_function
from cffi import FFI
ffi = FFI()
ffi.cdef("""
typedef long long time_t;
typedef struct timespec {
time_t tv_sec;
long tv_nsec;
...;
};
typedef struct stat {
struct timespec st_mtim;
...;
};
int lstat(const char *path, struct stat *buf);
""")
C = ffi.verify()
result = ffi.new("struct stat *")
p = C.lstat("foo.txt", result)
print("mtime = {0:d}.{1:09d}".format(result.st_mtim.tv_sec, result.st_mtim.tv_nsec))
在行为上与问题中的C程序相同. 产生输出:
This is identical in behavior to your C program in your question. This produces the output:
$ ./test.py
mtime = 1381711568.315075616
与您的C程序具有相同的精度:
Which has the same precision as your C program:
$ gcc test.c -o test
$ ./test
mtime = 1381711568.315075616
这篇关于使文件修改时间达到纳秒级精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!