Python | os.path.getmtime () method

Python Methods and Functions

os.path.getmtime() in Python is used to get the time of the last modification of 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.getmtime (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 modification of the specified path.

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

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

 
# OS and temporary module import

import os

import time

  
# Path

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

 
# Get time last
# modification of the specified
# path from era

modification_time = os.path.getmtime (path)

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

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

local_time = time.ctime (modification_time)

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

Exit :

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

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

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

 
# import os, time and system module

import os

import sys

import time

 
# Path

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

  
# Get last time
# modification of the specified
# path from epoch

try :

modification_time = os.path.getmtime (path)

print ( " Last modification time since the epoch: " , modification_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 (modification_time )

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

  

 
# the code above will print # path does not exist or is not available & # 39;
# 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