Stylized line drawing of mark playing the flute

File modification date/times in Python

A while back, I asked on StackOverflow, how to get file creation/modification date/times in Python.

It turns out, it's pretty easy via the os.stat() function.

Pass os.stat() a filename!

print os.stat("/tmp/file")

Get back a bunch of numbers!

posix.stat_result(st_mode=33188, st_ino=515666L, st_dev=64512L,

st_nlink=1, st_uid=1000, st_gid=1000, st_size=0L,

st_atime=1249609170, st_mtime=1249609170, st_ctime=1249609170)

Umm...so...what do all of those numbers actually mean?

ST_MODE ~ Inode protection mode. ST_INO ~ Inode number. ST_DEV ~ Device inode resides on. ST_NLINK ~ Number of links to the inode. ST_UID ~ User id of the owner. ST_GID ~ Group id of the owner. ST_SIZE ~ Size in bytes of a plain file; amount of data waiting on some special files. ST_ATIME ~ Time of last access. ST_MTIME ~ Time of last modification. ST_CTIME ~ The "ctime" as reported by the operating system. On some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time (see platform documentation for details).

My whole reason for finding out about os.stat() was to figure out which copy of a file was newer than another which can be done like this:

stat1 = os.stat(file1)stat2 = os.stat(file2)   diff = stat1.st_mtime - stat2.st_mtimeif diff > 0:    #file1 was modified more recentlyelif diff < 0:    #file2 was modified more recentlyelse    #files have the same modification date/time

My next goal is to work this into my Google Docs backup script.