0

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.

simonzack
  • 19,729
  • 13
  • 73
  • 118

2 Answers2

0

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}
simonzack
  • 19,729
  • 13
  • 73
  • 118
0

Instead of parsing the stat output, I would suggest to use the Python/C API to directly interface the stat source code as if it was a library.

It might be interesting to provide with an example, but I won't do it (at least for now) since I didn't play with the Python/C API for a long time and I'm currently busy with something else. I might challenge myself with that and update this answer later if ever I feel motivated.

Camion
  • 1,264
  • 9
  • 22