Python获取文件创建时间

2024年07月09日 Python获取文件创建时间 极客笔记

Python获取文件创建时间

在进行文件处理时,有时候我们需要获取文件的创建时间。Python提供了多种方法来获取文件的创建时间,本文将详细介绍如何利用Python获取文件的创建时间。

通过os.path模块获取文件创建时间

Python的os.path模块中包含了许多方法可以帮助我们获取文件的属性,其中就包括获取文件的创建时间。

下面是一个使用os.path模块获取文件创建时间的示例代码:

import os
import datetime

def get_creation_time(file_path):
    if os.path.exists(file_path):
        # 使用os.path.getctime()方法获取文件的创建时间
        timestamp = os.path.getctime(file_path)
        # 将时间戳转换为日期时间格式
        creation_time = datetime.datetime.fromtimestamp(timestamp)
        return creation_time
    else:
        return "File not found"

file_path = "example.txt"
creation_time = get_creation_time(file_path)
print(f"File creation time: {creation_time}")

在上面的代码中,我们定义了一个函数get_creation_time来接收文件路径作为参数,并使用os.path.getctime()方法来获取文件的创建时间。然后将时间戳转换为日期时间格式,并返回该时间。

接着我们调用这个函数并传入一个文件的路径,最后输出文件的创建时间。

运行以上代码,假设example.txt文件的创建时间为2022-01-01 12:00:00,则输出为:

File creation time: 2022-01-01 12:00:00

通过os.stat方法获取文件创建时间

除了使用os.path模块之外,还可以使用os.stat方法来获取文件的创建时间。os.stat方法会返回一个包含文件属性的stat_result对象,其中包含了文件的创建时间。

下面是一个使用os.stat方法获取文件创建时间的示例代码:

import os
import datetime

def get_creation_time(file_path):
    if os.path.exists(file_path):
        file_stat = os.stat(file_path)
        # 获取文件的创建时间
        creation_time = datetime.datetime.fromtimestamp(file_stat.st_ctime)
        return creation_time
    else:
        return "File not found"

file_path = "example.txt"
creation_time = get_creation_time(file_path)
print(f"File creation time: {creation_time}")

在上面的代码中,我们定义了一个函数get_creation_time来获取文件的创建时间。通过调用os.stat方法获取文件的属性,然后从st_ctime属性中获取文件的创建时间。

接着我们调用这个函数并传入一个文件的路径,最后输出文件的创建时间。

运行以上代码,假设example.txt文件的创建时间为2022-01-01 12:00:00,则输出为:

File creation time: 2022-01-01 12:00:00

通过Path对象获取文件创建时间

除了使用os.path模块和os.stat方法之外,Python的pathlib模块中的Path对象也提供了获取文件创建时间的方法。

下面是一个使用Path对象获取文件创建时间的示例代码:

from pathlib import Path
import datetime

def get_creation_time(file_path):
    file = Path(file_path)
    if file.exists():
        # 获取文件的创建时间
        creation_time = datetime.datetime.fromtimestamp(file.stat().st_ctime)
        return creation_time
    else:
        return "File not found"

file_path = "example.txt"
creation_time = get_creation_time(file_path)
print(f"File creation time: {creation_time}")

在上面的代码中,我们使用pathlib模块中的Path对象来处理文件路径,然后调用stat()方法获取文件属性,并从中获取文件的创建时间。

接着我们调用这个函数并传入一个文件的路径,最后输出文件的创建时间。

运行以上代码,假设example.txt文件的创建时间为2022-01-01 12:00:00,则输出为:

File creation time: 2022-01-01 12:00:00

通过以上三种方法,我们可以轻松地获取文件的创建时间,根据实际情况选择合适的方法来获取文件的创建时间。

本文链接:http://so.lmcjl.com/news/8155/

展开阅读全文