Home > Backend Development > Python Tutorial > How Can I Get File Creation and Modification Times Cross-Platform in Python?

How Can I Get File Creation and Modification Times Cross-Platform in Python?

Patricia Arquette
Release: 2024-12-12 20:44:10
Original
102 people have browsed it

How Can I Get File Creation and Modification Times Cross-Platform in Python?

Cross-Platform Approach to Retrieving File Creation and Modification Dates/Times

When working with files across various platforms, it becomes essential to access their creation and modification timestamps. To achieve this in a cross-platform manner, consider the following methods:

Modification Dates

Obtaining file modification dates is relatively straightforward using os.path.getmtime(path). This method returns the Unix timestamp indicating the last modification time of the file specified by path.

Creation Dates

Retrieving file creation dates is more challenging, as the approach varies depending on the operating system. Here's a breakdown:

  • Windows: Utilize os.path.getctime() or the .st_ctime attribute of os.stat().
  • Mac and Other Unix OS: Access the .st_birthtime attribute of os.stat().
  • Linux: Currently, direct access to creation dates isn't possible without writing a C extension for Python. However, the file's mtime (last modification time) can be obtained as an alternative.

Cross-Platform Implementation

To accommodate the platform-dependent creation date retrieval, a cross-platform function like the following can be employed:

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:
            return stat.st_mtime
Copy after login

The above is the detailed content of How Can I Get File Creation and Modification Times Cross-Platform in Python?. 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