ctime、atime和mtime—如何解释它们?

2024-06-01 14:07:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python编写一个程序,需要比较几个目录的atime、mtime和ctime。为此,我使用os.stat("my_directory/")。我得到的结果是一个包含这些时间的字符串。对于示例目录,我有:

st_atime=1418911410L
st_mtime=1418911410L
st_ctime=1404656050L

我的问题是我和这些数字有些混淆。我想知道这些数字是否可以转换成实际时间?或者,如果一个数字(比如说ctime)小于另一个数字(比如atime),这是否意味着ctime早于atime或晚于atime?我已经搜索了很多网站来学习这个,但是我的尝试没有成功。有人能帮我吗?提前谢谢。


Tags: 字符串程序目录示例os网站my时间
3条回答

ctime-上次更改文件索引节点的时间(例如,权限更改、文件重命名等)
mtime-上次更改文件内容的时间
上次访问文件的时间。

这些数字只是unix时间戳-有符号的32位整数,表示自1970年1月1日以来的秒数,也就是纪元。

是的,更小的数字=更早的时间。

通过使用stat模块解释stat()结果并从epoch转换为datetime,您可以从中获得一些有用的信息:

import os
import datetime

print datetime.datetime.fromtimestamp(os.stat(".").st_atime)

这将打印出一个日期时间对象,显示上次访问当前目录的时间:

datetime.datetime(2014, 12, 17, 7, 19, 14, 947384)

引用^{} function documentation

Note: The exact meaning and resolution of the st_atime, st_mtime, and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details.

对于Linux,系统文档是^{} manpage

struct timespec st_atim;  /* time of last access */
struct timespec st_mtim;  /* time of last modification */
struct timespec st_ctim;  /* time of last status change */

其中timespec^{}中定义:

Its time represents seconds and nanoseconds since the Epoch.

其中纪元是UNIX Epoch。该值越高,自该纪元(1970年1月1日,UTC午夜)以来经过的时间就越多。

Python^{} module以同样的方式及时处理,并且^{} module具有类方法,这些方法还将从这样的值中为您提供一个datetime对象:

>>> import datetime
>>> datetime.datetime.fromtimestamp(1418911410L)
datetime.datetime(2014, 12, 18, 14, 3, 30)

如上所示,这三个字段分别表示访问时间、修改时间和状态更改时间。

相关问题 更多 >