Make os.stat times readable in Python

I find myself needing to get file creation or modification times a lot. This is pretty trivial with using Python’s built in os.stat function. The problem is that it returns the file modification time in seconds since the epoch, which is not exactly the friendliest format to read. Here is an example:

>>> import os
>>> file = "H:\SSDC\common_functions\"
>>> modTime = os.stat(file).st_mtime
>>> print modTime

Now more power to you if you can look at that and get the date out of there, but I prefer a little more standard notation.

Luckily, this is doable. We need to first convert the epoch seconds that os.stat returned into a time_struct and then we can print that time_struct in a more readable manner.

Here is an example using the same file above:

>>> import time
>>> modTime2 = time.gmtime(os.stat(file).st_mtime)
>>> print modTime2
time.struct_time(tm_year=2012, tm_mon=4, tm_mday=13, tm_hour=13, tm_min=50, tm_sec=15, tm_wday=4, tm_yday=104, tm_isdst=0)
>>> modTime2_hr = time.strftime("%m/%d/%Y %H:%M:%S", modTime2)
>>> print modTime2_hr
04/13/2012 13:50:15

Python Standard Library – os.stat
Python Standard Library – time module

Comments are closed.