0
点赞
收藏
分享

微信扫一扫

os.path.getmtime 与 os.stat() 与 datetime.datetime.fromtimestamp

在Python中,os.path.getmtime(), os.stat()datetime.datetime.fromtimestamp()都是处理文件和时间的重要函数¹²³⁴⁵。

  • os.path.getmtime():这个函数用于获取指定文件的最后修改时间。它返回一个浮点数,表示自纪元(1970年1月1日00:00:00 UTC)以来的秒数³⁴。例如:

import os
timestamp = os.path.getmtime("your_file_path")

  • os.stat():这个函数用于获取指定文件的元数据,包括文件的大小、权限、所有者、创建时间、最后访问时间和最后修改时间等。它返回一个os.stat_result对象,这个对象包含了文件的所有元数据¹。例如:

import os
stat_info = os.stat("your_file_path")
timestamp = stat_info.st_mtime  # 获取文件的最后修改时间

  • datetime.datetime.fromtimestamp():这个函数用于将一个时间戳转换为一个datetime对象²⁵。例如:

import datetime
dt = datetime.datetime.fromtimestamp(timestamp)  # 将时间戳转换为datetime对象

通过组合使用这些函数,你可以获取文件的最后修改时间,并将其转换为一个易于理解的日期和时间¹²³⁴⁵。例如:

import os
import datetime

# 获取文件的最后修改时间
file_path = "your_file_path"  # 请替换为你的文件路径
timestamp = os.path.getmtime(file_path)
last_modified_time = datetime.datetime.fromtimestamp(timestamp)

print("文件的最后修改时间:", last_modified_time)

希望这个答案对你有所帮助!如果你有更多问题,欢迎随时向我提问。¹²³⁴⁵

源: 与必应的对话, 2023/11/10

(1) python - From stat().st_mtime to datetime? - Stack Overflow. https://stackoverflow.com/questions/39359245/from-stat-st-mtime-to-datetime.

(2) python - getmtime() vs datetime.now(): - Stack Overflow. https://stackoverflow.com/questions/58587891/getmtime-vs-datetime-now.

(3) Python os.path.getmtime() - 获取指定路径的最后一次修改时间|极客教程. https://geek-docs.com/python/python-os-module/python-os-path-getmtime-method.html.

(4) Python os.path.getmtime()用法及代码示例 - 纯净天空. https://vimsky.com/examples/usage/python-os-path-getmtime-method.html.

(5) python 时间格式 及 转换 文件时间说明_os.path.getmtime 转年月日-CSDN博客. https://blog.csdn.net/GUOGUO222/article/details/77870927.

举报

相关推荐

0 条评论