如何使用 Python 检查文件最后访问时间?

programmingpythonserver side programming

Python 中的文件最后访问日期时间可以通过多种不同的方式获取。以下 OS 模块方法将用于获取 Python 中的文件最后访问时间。

使用 os.path.getatime() 方法

在 Python 中,我们可以使用 os.path.getatime() 方法来检索路径的最近访问时间。我们需要验证访问时间的路径就是通过这种方法获取的。自纪元以来的时间量以浮点值的形式返回。

如果无法到达请求的路径或不存在,则会抛出一个 OSError。

语法

os.path.getatime(path)

示例 - 1

您要验证其上次访问时间的文件的路径是 filepath。

我们使用 os.path.getatime 读取的上次访问时间是 last_access_time。

datetime 模块用于在最后一行以人类可读的格式输出此时间。

以下是使用 os.path.getatime 方法检查文件上次访问时间的示例 -

import os import datetime filepath = r"C:\Users\Lenovo\Downloads\Work TP\trial.py" last_access_time = os.path.getatime(filepath) print('File Last access time is: {}'.format(datetime.datetime.fromtimestamp(last_access_time)))

输出

以下是上述代码的输出 -

File Last access time is: 2022-07-21 11:25:22.090214

示例 - 2

在下面的示例中,filepath 代表文件的路径,并返回文件自纪元以来的最近访问时间(以秒为单位)。然后可以将自纪元以来的时间转换为其他可读格式的时间戳。

此处,time.localtime() 的 struct time 函数将自纪元以来的秒数转换为本地时区。然后可以通过将该时间结构发送到 time.strftime() 来获取可读格式的时间戳。

我们可以通过修改 time.strftime() 中的格式字符串来接收仅日期和特定于我们应用程序的各种格式。

示例如下 -

import os import datetime import time filepath = r"C:\Users\Lenovo\Downloads\Work TP\trial.py" last_access_time_sinceEpoc = os.path.getatime(filepath) LastaccessTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(last_access_time_sinceEpoc))

输出

以下是上述代码的输出 -

LastaccessTime
'2022-07-21 11:25:22'

注意 − 除了使用 time.localtime(),我们还可以使用 time.gmtime() 来获取 UTC 时区中的最近访问时间,如下所示 −

LastaccessTime=time.strftime('%Y%m%d%H:%M:%S',time.gmtime(last_access_time_sinceEpoc))

使用 os.stat() 方法

它将文件的路径作为参数,并将文件的状态作为 os.stat 结果对象返回。它包括有关文件的许多详细信息,例如其模式、链接类型、访问或修改时间等。

语法

os.stat(filepath)

示例

访问字段 st_atime(该字段保存最近访问的时间,以秒为单位),以从 os.stat 结果对象中获取最近访问时间。然后,使用 time.ctime,我们可以将其转换为可以读取的格式。

以下是使用 os.stat 方法检查文件上次访问时间的示例 -

import os import stat import time # get the the stat_result object filePath = os.stat ("C:\Users\Lenovo\Downloads\Work TP\trial.py") # Get last access time FileLastaccessTime = time.ctime (filePath.st_atime)

输出

以下是上述代码的输出。

FileLastaccessTime
'Thu Jul 21 11:25:22 2022'

LINUX 中的文件最后访问时间

示例 - 1

我们可以使用 Linux stat 命令查看文件的访问、修改和更改时间。只需在命令中包含文件路径即可 −

$ stat code.py

输出

以下是上述命令的输出 -

File: code.py 
Size: 225                 Blocks: 8          IO Block: 4096     regular file 
Device: 801h/2049d        Inode: 274798       Links: 1 
Access: (0644/-rw-r--r--) Uid: ( 1000/ sarika) Gid: ( 1000/ sarika) 
Access: 2022-07-28 11:50:49.134939844 +0530 
Modify: 2022-07-28 11:50:26.683334414 +0530 
Change: 2022-07-28 11:50:26.683334414 +0530 
 Birth: 2022-07-27 09:59:26.061843845 +0530

示例 - 2

如果您想使用 ls 查看文件的访问时间,请在命令中添加 −u 参数 −

$ ls -l code.py

输出

以下是上述命令的输出 -

-rw-r--r-- 1 sarika sarika 225 Jul 28 11:50 code.py

相关文章