[CentralOH] os.stat

William McVey wam at cisco.com
Mon May 12 16:30:43 CEST 2008

On Sun, 2008-05-11 at 22:49 -0400, Mark Erbaugh wrote:
> I'm working on a program that needs to extract a date* from a file and
> I'm using the os.stat function.  I'm running Ubuntu Linux.
> import os
> import stat
> import datetime
> datetime.datetime.fromtimestamp(os.stat[stat.ST_CTIME])

I'm not sure if you were intending this to be illustrative, or as a real
code sample. Since it looks like the latter, it should probably be
pointed out that this doesn't look right. You probably want:
        >>> your_path = "/etc/passwd"
        >>> ctime = datetime.datetime.fromtimestamp(os.stat(your_path).st_ctime)
        >>> ctime
        datetime.datetime(2008, 1, 2, 10, 29, 50)

> On several files that I've tested, this code returns the same date that
> I get from ls -l. 

The timestamp from 'ls -l' output is by default modification time. You
need to add the '-c' option for ls to display the ctime.

> However, for one file, the time is off by about 8
> seconds.  It this a rounding issue or is it actually retrieving a
> different date?  Or is it something else altogether?

Your python program is extracting the ctime and 'ls' is displaying the

> * ideally the creation date, but from the Python docs, it looks like
> under Unix (and I assume Linux) it is actually the date of the last
> metadata change (whatever that is).

The ctime is updated whenever the inode of the file is updated. This
includes operations on the owner, group, permission, and notably link
count. That last one is notable because in general, only the owner can
update the ownership, group ownership or permission of a file, but just
about anyone can change the link count of a file, so long as there is a
writeable directory on the filesystem on which the target file exists. I
point this out because if you're really looking for creation date, you
should well be aware that "settling on" ctime may very well put that
timestamp under the control of arbitrary (depending on how locked down
the partition is). On the other hand, the mtime (modification time) puts
the time stamp only under the control of those who have been granted
write access to the file.

 -- William

More information about the CentralOH mailing list