If I do a stat
command on a file under Btrfs, I get something like the following output:
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
How do I get the 4 times in Python?
I tried doing os.stat()
, however birth time doesn't exist there. I found crtime in past answers, but that requires sudo
, which stat
doesn't.
I could parse stat
results myself, but ideally there is something that already exists.
Here's my solution calling the stat
command & parsing the output manually. Please feel free to post solutions that don't require doing this.
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=%x\n%y\n%z\n%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
Ah example output of the function looks like:
{'access': 1583824344829877823,
'modify': 1583824346649884067,
'change': 1583824346649884067,
'birth': 1583813803975447216}