Home >Backend Development >Python Tutorial >How Can I Reliably Get File Creation and Modification Times Across Different Operating Systems?
Cross-Platform File Creation and Modification Date/Time Retrieval
Obtaining the file creation and modification dates/times across different operating systems can be a complex task.
Modification Dates
Getting file modification dates cross-platform is relatively straightforward using os.path.getmtime(), which provides the Unix timestamp of the last modification.
Creation Dates
For file creation dates, the process becomes more intricate due to platform-specific implementations:
Cross-Platform Code
Combining these platform-specific approaches, a cross-platform code snippet is as follows:
import os import platform def creation_date(path_to_file): """ Try to get the date that a file was created, falling back to when it was last modified if that isn't possible. See http://stackoverflow.com/a/39501288/1709587 for explanation. """ if platform.system() == 'Windows': return os.path.getctime(path_to_file) else: stat = os.stat(path_to_file) try: return stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. return stat.st_mtime
This code first checks the platform to apply the appropriate method. On Windows, it uses os.path.getctime(), while on Mac and some Unix-based OSes, it attempts to retrieve the creation date using .st_birthtime. For Linux, it falls back to the modification date obtained through .st_mtime.
The above is the detailed content of How Can I Reliably Get File Creation and Modification Times Across Different Operating Systems?. For more information, please follow other related articles on the PHP Chinese website!