【问题标题】:How to use Python to get a file's "last accessed" time the way Windows defines it?如何使用 Python 以 Windows 定义文件的方式获取文件的“最后访问”时间?
【发布时间】:2021-10-15 08:39:49
【问题描述】:

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

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

【问题讨论】:

  • 你试过getmtime()吗?
  • 是的,但它似乎只考虑了上次修改文件本身的时间,所以很遗憾它没有工作。

标签: python windows file time


【解决方案1】:

你可以试试这个代码sn-p。

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

【讨论】:

    猜你喜欢
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多