Search code examples
pythonwindowswmic

Get accurate file creation date from Python on Windows 10


I'm trying to get accurate (with ms resolution) creation date of a file using python.

The way to get accurate creation date on Window is to use wmic. So I've prepared a simple shell command to read the creation date:

wmic datafile where name="C:\\Users\\Public\\test.txt" get creationdate | findstr /brc:[0-9]

that runs ok crom a CMD shell on Win10 (if the file is there) I then tried to run the same command from python using subprocess:

import subprocess
from subprocess import check_output, STDOUT, CalledProcessError
cmd = 'wmic datafile where name="C:\\Users\\Public\\test.txt" get creationdate | findstr /brc:[0-9]'
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print( "program output:", out)


try:
    o = check_output(cmd, stderr=STDOUT, shell=True)
    returncode = 0
except CalledProcessError as ex:
    o = ex.output
    returncode = ex.returncode
    if returncode != 1: # some other error happened
        raise
finally:
    print(o)

But I got the same error message:

Node - username ERROR: Description = Invalid query

do you have any suggestion on how to get more info on the error of fix it?


Solution

  • import subprocess
    from subprocess import check_output, STDOUT, CalledProcessError
    cmd = 'wmic datafile where name="C:\\\\Users\\\\Public\\\\test.txt" get creationdate | findstr /brc:[0-9]'
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    print( "program output:", out.decode().rstrip())
    

    out.decode().rstrip() returns a string, something like '20210113222350.636280+060'.

    Explanation:

    1. Escape all \ (Reverse Solidus) in Windows path.
    2. Check returned value type: type(out) ==> <class 'bytes'>; decode it to string.
    3. Strip all trailing whitespaces using the method rstrip().

    Note: import os; os.path.getctime("C:\\Users\\Public\\test.txt") returns a float value 1610573030.6362805 which is an epoch time format, imho (GMT Wednesday, 13 January 2021 21:23:50.636).