In this article we will discuss different ways to get the last modification date & time of a file and how to convert them into different formats.

Get last modification time of a file using os.stat()

It returns the status of file in the form of an os.stat_result object. It contains information related to a file like it’s mode, link type, access, creation or modification time etc.

To get the last modification time from os.stat_result object access the property ST_MTIME, that contains the time of
most recent file modification in seconds. Then we can covert that to readable format using time.ctime() i.e.

Output:

Get last modification time of a file using os.path.getmtime()

Python’s os.path module provides an another API for fetching the last modification time of a file i.e.

Here, path represents the path of file and it returns the last modification time of file in terms of number of seconds since the epoch. Then we can convert the time since epoch to different readable format of timestamp. Let’s see an example,

Get last modification time using os.path.getmtime() & time.localtime()

Output:

time.localtime() converts the seconds since epoch to a struct_time in local timezone. Then by passing that time struct to time.strftime() we can get timestamp in readable format.

By changing format string in time.strftime() we can get date only and also in other format specific to our application i.e.

Output:

Get last modification time using os.path.getmtime() & datetime.fromtimestamp()

Instead of time.localtime() we can also use another function datetime.fromtimestamp() to convert seconds since epoch to time object. Then we can call time.strftime() to convert that to readable format. For example,

Output:

Get last modification time of a file in UTC Timezone

To get the last modification time in UTC timezone use datetime.utcfromtimestamp() i.e.

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.