Python 如何检查文件的最后访问时间
在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'
注意
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
在命令中添加 -u 参数,如果你想使用ls命令查看文件的访问时间 –
$ ls -l code.py
输出
以下是上述命令的输出结果:
-rw-r--r-- 1 sarika sarika 225 Jul 28 11:50 code.py