Python os.path.getatime() Method

Python os.path.getatime() Method

  1. Syntax of os.path.getatime() Method
  2. Example 1: Use the os.path.getatime() Method in Python
  3. Example 2: Handling Errors in the os.path.getatime() Method

Python os.path.getatime() method is an efficient way of knowing the timestamp of any specified file or folder.

Syntax of os.path.getatime() Method

os.path.getatime(path)

Parameters

path - an address object of a file system path or a symlink. The object can either be an str or bytes.

Return

The return type of this method is a floating-point value representing the recent access time of a specified path in seconds.

Example 1: Use the os.path.getatime() Method in Python

import os

import time

fd = os.open( "File.txt", os.O_RDWR|os.O_CREAT )

path ="/home/File.txt"

atime = os.path.getatime(path)

print("The last access time of this file since epoch:", atime)

ltime = time.ctime(atime)

print("The Last access time of this file, in Local time, is:", ltime)

Output:

The last access time of this file since epoch: 1659640125.8796265
The Last access time of this file, in Local time, is: Wed Aug 3 19:08:45 2022

The epoch means where the time starts for a particular system and is platform-dependent. For example, in Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC).

Example 2: Handling Errors in the os.path.getatime() Method

import os

import time

import sys

fd = os.open( "File.txt", os.O_RDWR|os.O_CREAT )

path ="/home/user/File.txt"

try:
    atime = os.path.getatime(path)
    print("The last access time of this file is:", atime)

except OSError:
    print("The path '%s' does not exist or is inaccessible." %path)
    sys.exit()

ltime = time.ctime(atime)
print("The Last access time of this file, in Local time, is:", ltime)

Output:

The path '/home/user/File.txt' does not exist or is inaccessible.

The above code raises an OSError exception because the file does not exist. You might have a similar error if the file is inaccessible or the path is invalid.

Musfirah Waseem avatar Musfirah Waseem avatar

Musfirah is a student of computer science from the best university in Pakistan. She has a knack for programming and everything related. She is a tech geek who loves to help people as much as possible.

LinkedIn

Related Article - Python OS

  • Python os.set_handle_inheritable() Method
  • Python os.set_inheritable() Method
  • Python os.stat_result Class
  • Python os.renames() Method
  • Python os.get_handle_inheritable Method
  • Python os.get_inheritable Method