首页 > 解决方案 > 如何使用 Python 以 Windows 定义文件的方式获取文件的“最后访问”时间?

问题描述

我正在尝试使用 Python 根据 Windows 获取文件的“最后访问”时间,这基本上是最后一次对文件进行任何操作,包括例如复制或重命名。但是 Python 的 getatime() 显然只计算上次实际查看或修改文件的时间,这对我不起作用。是否有任何图书馆或任何我可以使用的东西?

如果重要的话,我要解决的问题是获取文件在文件夹中的确切顺序。有些是下载的,有些可能是从另一个文件夹剪切和粘贴的,在这种情况下,它们会保留原始文件的创建时间(这就是为什么 getctime() 对此不起作用,遗憾的是)。

标签: pythonwindowsfiletime

解决方案


你可以试试这个代码片段。

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()

推荐阅读