Peter Smit Peter Smit - 1 year ago 80
Python Question

Is ctime always <= mtime?

When using os.stat() in Python, can I assume that st_ctime is always less then or equal to st_mtime? If not, why not?

The code will always run on Linux, but if there is a difference between OSes, that would be good to know.

Answer Source

There are some situations in which this assumption could prove invalid (and would depend very much on the OS implementation):

  • Timezones. If you create a file in, say, UTC+4, and then modify it when the current timezone is UTC-8, and the operating system doesn't use UTC for all timestamps behind-the-scenes, the modified time will be less than the created time. It would be surprising for a modern operating system (Windows, OSX, one of the BSDs or Linux) to have mtime < ctime in this case.
  • Resetting the OS time. This could affect the modified time to create this situation. I would say it would be much more likely that you would have mtime < ctime without complaint from the OS in this case, assuming there aren't checks in place in the filesystem driver to avoid this case.
  • Modifying the times through system calls. Again, the filesystem driver may have checks in place to avoid unusual situations such as this.

Both of these are reproducable: your best bet is to take a variety of operating systems that you plan on targeting and testing this behaviour. All I can provide is speculation.

Also, st_ctime is not necessarily the "created time", but rather the time of the "last status change" (source). utime marks the ctime of the file to be updated (source) and it's parameter of type "utimbuf" has no member for ctime. So it is technically possible for ctime to be a time past mtime if the operating system and filesystem permit it. The os.stat documentation actually mentions this:

platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows

Whilst Python hides a lot of the C side of things, os.stat and friends are all built upon the same base C system calls so the specification for them is a great place to look for more information.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download