天天看点

python时间函数纳秒_python – 获取纳秒级精度的文件修改时间

我需要为遍历文件系统树的Python 2程序中的每个文件获取完整的纳秒精度修改时间戳.我想在Python本身中这样做,因为为每个文件生成一个新的子进程会很慢.

通过查看stat结果的st_mtime_nsec字段,从Linux上的C库,you can get nanosecond-precision timestamps开始.例如:

#include

#include

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).

同样,日期–rfc-3339 = ns –reference = / prints 2013-10-01 22:43:34.213703287 00:00.

Python(2.7.3)的os.path.getmtime(filename)和os.lstat(filename).st_mtime将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位数字是正确的,可能是由于浮点错误.

解决方法:

或者,您可以使用cffi库,它与Python 2一起使用以下代码(在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程序的行为相同.

这会产生输出:

$./test.py

mtime = 1381711568.315075616

其精度与C程序相同:

$gcc test.c -o test

$./test

mtime = 1381711568.315075616

标签:python,filesystems,datetime,linux,precision