1

In Python (and Python2) on macOS, when I use

os.path.getmtime('/path/to/a/symlink')

I get the modification time of the symlink's target. - How do I get instead the modification time of the symlink itself?

halloleo
  • 9,216
  • 13
  • 64
  • 122
  • tried `os.stat(filename)`? – Lei Yang Apr 07 '22 at 04:41
  • Makes sense. Great find. @LeiYang would you like to make it into a proper answer? – halloleo Apr 07 '22 at 07:55
  • i'm afraid i don't understand the internal difference either. – Lei Yang Apr 07 '22 at 09:09
  • Is the os.path.getmtime() with symlink behavior documented anywhere? I need the current behavior and my code will stop working if a future python release changes os.path.getmtime() to return the mtime of the symlink itself. – Steve Nov 15 '22 at 19:13
  • 1
    @Steve The doco of [getmtime](https://docs.python.org/3/library/os.path.html#os.path.getmtime) does _not_ go into detail, but the doco for other functions in `os.path` gives hints. E.g. for [isfile](https://docs.python.org/3/library/os.path.html#os.path.isfile) it says: "Return True if path is an existing regular file. **This follows symbolic links, so both islink() and isfile() can be true for the same path.**" So I don't think you need to worry the behaviour of getmtime will change. – halloleo Nov 16 '22 at 04:04

1 Answers1

1

As @LeiYang hinted in a comment, use os.lstat instead.

However, the result is not an mtime float, but rather a stat_result structure.

How to extract the mtime information see stat — Interpreting stat() results in the Python documentation.

halloleo
  • 9,216
  • 13
  • 64
  • 122