Home >Backend Development >Python Tutorial >How Can I Get a File's Creation and Modification Timestamps Reliably Across Different Operating Systems?
Accessing File Creation and Modification Date/Times Cross-Platform
Retrieving file modification date/times cross-platform is straightforward with os.path.getmtime(path). For a more granular approach, consider the following nuances:
Windows
For creation dates on Windows, utilize os.path.getctime(path). This retrieves the file's "creation time" (ctime), which is specific to Windows.
Mac and Unix (Except Linux)
Access creation dates via the .st_birthtime attribute of the os.stat() result.
Linux
Unfortunately, retrieving creation dates on Linux is currently not feasible without implementing a Python C extension. Accessing st_crtime, which stores creation dates on Linux file systems, is restricted by limitations in the Linux kernel. As a fallback, use os.path.getmtime() to obtain the content modification timestamp.
To cover all platforms, a versatile approach could be:
import os import platform def creation_date(path): if platform.system() == 'Windows': return os.path.getctime(path) else: stat = os.stat(path) try: return stat.st_birthtime except AttributeError: return stat.st_mtime
The above is the detailed content of How Can I Get a File's Creation and Modification Timestamps Reliably Across Different Operating Systems?. For more information, please follow other related articles on the PHP Chinese website!