How do I get the time a file was last modified in Python?

Question:

Assuming the file exists (using os.path.exists(filename) to first make sure that it does), how do I display the time a file was last modified? This is on Linux if that makes any difference.

Asked By: Bill the Lizard

||

Answers:

os.stat()

import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print("Modification time: {}".format(statbuf.st_mtime))

Linux does not record the creation time of a file (for most fileystems).

Answered By: Douglas Leeder
>>> import os
>>> f = os.path.getmtime('test1.jpg')
>>> f
1223995325.0

since the beginning of (epoch)

Answered By: Jack

New for python 3.4+ (see: pathlib)

import pathlib

path = Path('some/path/to/file.ext')
last_modified = path.stat().st_mtime
Answered By: Brian Bruggeman
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.