如何在 Python 中获取最后文件访问时间(atime)

要在 Python 中获取 myfile.txt 的最后访问时间,使用

get_atime_example.py
import os
from datetime import datetime

datetime.fromtimestamp(os.stat("myfile.txt").st_atime)

你也可以使用此实用函数:

last_file_access_time.py
import os
from datetime import datetime

def last_file_access_time(filename):
    """
    获取表示给定文件最后访问时间的 datetime()。
    返回的 datetime 对象是本地时间
    """
    return datetime.fromtimestamp(os.stat(filename).st_atime)

注意 os.stat("myfile.txt").st_atime 返回类似 1563738878.1278138 的 Unix 时间戳(自 1970-1-1 00:00:00 以来经过的秒数)。此时间戳和我们将其转换成的 datetime 是本地时间。

记住如果用户在其文件系统上禁用了访问时间(例如为了节省 SSD 上的写入),你无法找出最后访问日期。


Check out similar posts by category: Python