Operating systems stores important timestamps relevant to a file or a directory, they include:

  • Creation time: The time when the file or directory was created.
  • Accessed time: The time when the file or directory was last accessed (i.e. read from or written to).
  • Modified time: The time when the file or directory was last modified.

The os modules in the standard library includes the path sub-module which contains essential functions for working with and manipulating paths. In this article we will look at three of these functions i.e getctime(), getatime() and getmtime() which are used to retrieve the creation time, accessed time and modified time of a file/directory , respectively.

To use any of the functions we will first need to import it in our program as follows.

from os.path import getctime, getatime, getmtime

Get creation time

The getctime() function is used to get the time when a file or a directory was created. 

getctime(p)
p String representing the path to the file/directory.

The input value p should a path(relative or absolute) to the target file/directory. If the path given is invalid i.e does not exist, a  FileNotFoundError exception will be raised. The function returns a timestamp for the time when the file was created.

from os.path import getctime
from time import ctime

p = r"C:\user\john\desktop\project\tests.py"
timestamp = getctime(p)
friendly_time = ctime(timestamp)

print(timestamp)
print(friendly_time)

1685920612.037839
Mon Jun  5 02:16:52 2023

The getctime() function returns a timestamp since the epoch as a floating point value,  this is not a human friendly time representation, we used the ctime() function from the time module to transform the timestamp into a human friendly format.

Get access time

To get the last time that a file was accessed, we use the getatime() function.

The syntax is similar to the af the getctime() function, above.

getatime(p)
from os.path import getatime
from time import ctime

p = r"C:\user\john\desktop\project\tests.py"
timestamp = getatime(p)
friendly_time = ctime(timestamp)

print(timestamp)
print(friendly_time)

1698280694.7601051
Thu Oct 26 03:38:14 2023 

Get modification time

Modification time refers to the last time when a file or a directory was modified. We use the getmtime() function to get the modification time.

from os.path import getmtime
from time import ctime

p = r"C:\user\john\desktop\project\tests.py"
timestamp = getmtime(p)
friendly_time = ctime(timestamp)

print(timestamp)
print(friendly_time)

1697252312.155745
Sat Oct 14 05:58:32 202 

As earlier mentioned, a FileNotFoundError exception will be raised on all the three functions if the input value does not represent a valid path to an existing file or directory.

from os.path import getmtime

getmtime('/invalid')