Python | os.path.getatime () method

Python Methods and Functions

os.path.getatime() in Python is used to get the last access time to a specified path. This method returns a floating point value that represents the number of seconds since the beginning of the epoch. This method raises an OSError if the file does not exist or is not available.

Note: The epoch represents the point where time begins. It depends on the platform. For Unix, the era of — January 1, 1970 00:00:00 UTC.

Syntax: os.path.getatime (path)

Parameter:
path : A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a floating-point value of class `float` that represents the time (in seconds) of last access of the specified path.

Code # 1 : Using the os.path.getatime () method

# Python program to explain the os.path.getatime () method

 
# OS and temporary module import

import os

import time

  
# Path

path = `/ home / User / Documents / file.txt`

 
# Get last time
# access to the specified
# path from the era

access_time = os.path.getatime (path)

print ( "Last access time since the epoch:" , access_time)

 
# convert time to
# seconds since the beginning of the epoch
# local time

local_time = time.ctime (access_time)

print ( "La st access time (Local time): " , local_time)

Exit:

 Last access time since the epoch: 1558447897.0442736 Last access time (Local time): Tue May 21 19:41:37 2019 

Code # 2: Error handling when using the os.path.getatime () method

# Python program to explain the method os.path.getatime ()

 
# import os, time module and systems

import os

import sys

import time

 
# Path

path = `/ home / User / Documents / file2.txt`

 
# Get last time
# access to the specified
# path from the era

try :

access_time = os.path.getatime (path)

  print ( "Last access time since the epoch:" , access_time)

  

except OSError:

print ( "Path`% s` does not exists or is inaccessible " % path)

sys.exit ()

 
# convert time to
# seconds since the beginning of the epoch
# local time

local_time = time.ctime (access_time)

print ( "Last access time (Local time):" , local_time)

 

 
# the code above will print
# "The file does not exist or is not available"
  # if the specified path is not
# exists or is not available

 

Exit:

 Path `/ home / User / Documents / file2.txt` does not exists or is inaccessible 

Link: https://docs.python.org/3/library/os.path.html





Get Solution for free from DataCamp guru