在Btrfs上获取Python中的所有4个时间戳



如果我在Btrfs下的文件上执行stat命令,我会得到如下输出:

Access: 2020-03-10 14:52:58.095399291 +1100
Modify: 2020-02-21 02:36:29.595148361 +1100
Change: 2020-02-21 17:20:59.692104719 +1100
Birth: 2020-02-20 17:59:44.372828264 +1100

如何在Python中获得4次?

我试过做os.stat(),但那里不存在出生时间。我在过去的答案中找到了crtime,但这需要sudo,而stat没有。

我可以自己解析stat结果,但理想情况下已经存在一些内容。

以下是我的解决方案,调用stat命令&手动解析输出。请随意发布不需要这样做的解决方案。

import datetime
import re
import subprocess
def stat_ns(path):
'''
Python doesn't support nanoseconds yet, so just return the total # of nanoseconds.
'''
# Use human-readable formats to include nanoseconds
outputs = subprocess.check_output(['stat', '--format=%xn%yn%zn%w', path]).decode().strip().split('n')
res = {}
for name, cur_output in zip(('access', 'modify', 'change', 'birth'), outputs):
# Remove the ns part and process it ourselves, as Python doesn't support it
start, mid, end = re.match(r'(d{4}-d{2}-d{2} d{2}:d{2}:d{2}).(d{9}) ([+-]d{4})', cur_output).groups()
seconds = int(datetime.datetime.strptime(f'{start} {end}', '%Y-%m-%d %H:%M:%S %z').timestamp())
ns = 10**9 * seconds + int(mid)
res[name] = ns
return res

啊,函数的输出示例如下:

{'access': 1583824344829877823,
'modify': 1583824346649884067,
'change': 1583824346649884067,
'birth': 1583813803975447216}

我建议使用Python/C API直接接口stat源代码,而不是解析stat输出,就像它是一个库一样。

提供一个示例可能很有趣,但我不会这么做(至少现在(,因为我很长一段时间没有使用Python/C API了,目前我正忙于其他事情。如果我有动力的话,我可能会用这个来挑战自己,并在以后更新这个答案。

最新更新