3

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?

Filartrix
  • 157
  • 1
  • 10
  • 1
    Just a guess, but python converts the call to `cmd.exe /c your-command-here` and I suppose that could mess with the quotes. I don't have windows up to test, but perhaps making `"` into `""` may help. – tdelaney May 19 '21 at 16:32
  • 1
    You can do wmi calls programatically via the `win32` api as outlined by Tim Golden [here](http://timgolden.me.uk/python/wmi/tutorial.html). Or perhaps more directly though [`fileapi`](http://timgolden.me.uk/pywin32-docs/win32file.html). – tdelaney May 19 '21 at 16:36
  • Why not just use [os.path.getctime](https://docs.python.org/3/library/os.path.html#os.path.getctime)? – viilpe May 20 '21 at 07:45

1 Answers1

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

JosefZ
  • 28,460
  • 5
  • 44
  • 83