python

How to get file creation and modification date in Python

In this tutorial, we are going to see different ways to get file creation and modification date and how to convert it to different formats in Python.
 

How to get file modification date in Python

To get the file modification date, just call os.path.getmtime(path) which is compatible on a different platform (like Windows, Linux, Mac, etc…) and you will get the last modification date of the file given in parameter. Example:

import os.path, time

print("Last modification: %s" % time.ctime(os.path.getmtime("file.txt")))

Output:

Last modification: Sat Apr 27 15:14:47 2019
 

How to get file creation date in Python

Getting the file creation date, is a bit complex, because it depends on the platform, even between the three major operating systems (Windows, Linux, Mac)

The file creation date is the time when it was created. The first thing to do is to import the “os” and “time” modules into the script.
 
On windows

import os.path, time

print("Creation date: %s" % time.ctime(os.path.getctime("file.txt")))

On Other system

import os
from datetime import datetime

def get_creation_date(file):
    stat = os.stat(file)
    try:
        return stat.st_birthtime
    except AttributeError:
        # We are probably on Linux. No way to get the creation date, only the last modification date.
        return stat.st_mtime

# Convert Timestamp to datetime
creation_date = datetime.fromtimestamp(get_creation_date('file.txt'))
print("Creation date: %s" % creation_date)

Output:

Creation date: 2019-03-01 00:35:15.590904
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *