python - 在 Windows 10 上从 Python 获取准确的文件创建日期

标签 python windows wmic

我正在尝试使用 python 获取文件的准确(使用 ms 分辨率)创建日期。

在 Window 上获取准确创建日期的方法是使用 wmic . 所以我准备了一个简单的 shell 命令来读取创建日期:

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

在 Win10 上通过 CMD shell 运行正常(如果文件存在) 然后我尝试使用子进程从 python 运行相同的命令:

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)

但是我得到了同样的错误信息:

Node - username ERROR: Description = Invalid query

关于如何获取有关修复错误的更多信息,您有什么建议吗?

最佳答案

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()返回一个字符串,类似于'20210113222350.636280+060' .

解释:

  1. 转义所有\ Windows 路径中的 (Reverse Solidus)。
  2. 检查返回值类型:type(out) ==> <class 'bytes'> ;将其解码为字符串。
  3. 使用 rstrip() 方法去除所有尾随空格.

备注:import os; os.path.getctime("C:\\Users\\Public\\test.txt")返回一个 float1610573030.6362805这是一种纪元时间格式,恕我直言 (GMT Wednesday, 13 January 2021 21:23:50.636)。

关于python - 在 Windows 10 上从 Python 获取准确的文件创建日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67607136/

相关文章:

python - 如果错误,执行此操作并返回,否则继续在一行中执行

python - 检查字典中是否存在特定的键和值

json - 什么是 (ERR! code ENOLOCAL npm ERR!) Could not install because of an error?

windows - Carbon Accessibility API - 跨空间获取窗口信息

batch-file - 仅从 dll 文件中获取版本中的数字

python - 编写异步 HTTP 库是否需要 Python 的 AsyncIO 协议(protocol)?

python - 计算目录中大量文件的最快/最简单方法是什么(在 Linux 中)?

windows - 如何在 AWS Windows 实例的 CloudFormation 脚本中将 DeleteOnTermination 设置为 true?

java - 使用 Bat 文件启动 Java 应用程序(如果尚未启动)

string - 在Powershell中将字符串变量作为参数传递