python - 如何使用 Python 以 Windows 定义文件的方式获取文件的“最后访问”时间?
问题描述
我正在尝试使用 Python 根据 Windows 获取文件的“最后访问”时间,这基本上是最后一次对文件进行任何操作,包括例如复制或重命名。但是 Python 的 getatime() 显然只计算上次实际查看或修改文件的时间,这对我不起作用。是否有任何图书馆或任何我可以使用的东西?
如果重要的话,我要解决的问题是获取文件在文件夹中的确切顺序。有些是下载的,有些可能是从另一个文件夹剪切和粘贴的,在这种情况下,它们会保留原始文件的创建时间(这就是为什么 getctime() 对此不起作用,遗憾的是)。
解决方案
你可以试试这个代码片段。
import os
import stat
import time
def get_file_event_time():
filePath = '/path/to/file.extention'
print("**** Get File Last Access time using os.stat() ****")
# get the the stat_result object
fileStatsObj = os.stat ( filePath )
# Get last access time
accessTime = time.ctime ( fileStatsObj [ stat.ST_ATIME ] )
print("File Last Access Time : " + accessTime)
print("**** Get File Creation time using os.stat() *******")
# get the the stat_result object
fileStatsObj = os.stat ( filePath )
# Get the file creation time
creationTime = time.ctime ( fileStatsObj [ stat.ST_CTIME ] )
print("File Creation Time : " + creationTime)
print("**** Get File Last Access time using os.path.getatime() ****")
# Get last access time of file in seconds since epoch
accessTimesinceEpoc = os.path.getatime(filePath)
# convert time sinch epoch to readable format
accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(accessTimesinceEpoc))
print("File Last Access Time : " + accessTime)
print("**** Get File Last Access time using os.path.getatime() in UTC Timezone****")
accessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(accessTimesinceEpoc))
print("File Last Access Time : " + accessTime + ' UTC' )
print("**** Get File creation time using os.path.getctime() ****")
# Get file creation time of file in seconds since epoch
creationTimesinceEpoc = os.path.getctime(filePath)
# convert time sinch epoch to readable format
creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(creationTimesinceEpoc))
print("File Creation Time : " + creationTime )
print("**** Get File creation time using os.path.getctime() in UTC Timezone ****")
creationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(creationTimesinceEpoc))
print("File Creation Time : ", creationTime , ' UTC' )
get_file_event_time()
推荐阅读
- sparql - SPARQL 属性搜索 (MarkLogic)
- python - 通过 PySpark 将 Kafka 数据摄取到 HBase - 调用 None.org.apache.spark.streaming.api.java.JavaStreamingContext 时发生错误
- sql-server - 全文搜索计划抛出异常
- pdftron - 只读表格填写 - PDFTron
- ios - 在 ViewController 中显示自定义 UIView
- c# - 按点链接 lambda 表达式
- json - 配置单元将 json 记录解析为 NULL
- java - Java:带有“准备X元素”的并行流管道->迭代器()
- javascript - 正则表达式语法是否提供了一种转义整个字符串的方法,而不是一个一个地转义字符?
- r - 如何在 r 中绘制邓恩指数