Python os.path.getatime() Method

Python os.path.getatime() method is used to get the last access time of a file or directory. 

Syntax

os.path.getatime(path)

Parameters

Name Description
path (string) The path of the file or directory.

Return value

It returns the time of the file’s last access or directory specified by path. The time is expressed in seconds since the epoch, January 1, 1970, 00:00:00 (UTC).

Example 1: Getting the last Access time of a file

Understanding of Python os.path.getatime() Method

Here is the “file.txt,” which I accessed just now, on Feb 7th, 2024.

Let’s check the last access time visually by getting its info:

Output of GUI that suggest the last access time

Let’s write a code that will get the exact time as the above screenshot:

import os
import time

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/file.txt'
access_time = os.path.getatime(path)
print("Last access time:", time.ctime(access_time))

Output

Last access time: Wed Feb 7 00:03:35 2024

Example 2: Handling non-existent file

Handling non-existent file

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/non_existent.txt'

try:
  access_time = os.path.getatime(path)
  print("Last access time:", access_time)
except FileNotFoundError:
  print("File not found.")

Output

File not found.

And we handled the FileNotFoundError.

This method is helpful for file system operations where you need information about when a file was last accessed.

It can be used for tasks like cleaning up old files, auditing file usage, or tracking changes in a directory.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.