Home > Backend Development > Python Tutorial > How Can I Get a File's Creation and Modification Timestamps Reliably Across Different Operating Systems?

How Can I Get a File's Creation and Modification Timestamps Reliably Across Different Operating Systems?

Mary-Kate Olsen
Release: 2024-12-12 21:49:10
Original
993 people have browsed it

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template