Python Get the Last Modified Date of a File: A Beginner Guide – Python Tutorial

By | April 10, 2020

The last modified time is a basic attribution of a file, it is easy to get in python. In this tutorial, we will use an simple example to show python beginners how to do.

Preliminary

You should import python os package.

import os

Get the last modified time of a file in python

lastmodified= os.stat('demo.png').st_mtime

print(lastmodified)

Run this code, you will get the last modified time is:

1568554988.7396924

The result is a timestamp, which is not friendly. We can format it.

Format the last modified time of a file

We can use python datetime model to format a timestamp. Here is an example:

from datetime import datetime
lastmodified = datetime.fromtimestamp(lastmodified)
print(lastmodified)

The result will be:

2019-09-15 21:43:08.739692

However, it is not a standard time format, we can format it again.

lastmodified = lastmodified.strftime('%Y-%m-%d %H:%M:%S')
print(lastmodified)

The last modified time will be:

2019-09-15 21:43:08

Leave a Reply