如何在Python中获取文件创建和修改日期或时间?
时间戳是一个字符序列,表示事件的发生。在计算机科学中广泛需要时间戳。这存在不同的精度和准确度,即一些时间戳对于偶数的出现具有高达毫秒的精度,而另一些则没有。这允许存在不同形式(和标准)的时间戳。在本文中,我们将介绍查找文件创建和修改时间戳的方法。我们将使用具有以下属性的文件进行演示。
我们将使用 os 库中的 path 模块中的getctime()和getmtime()函数来获取文件的创建和修改时间。上述函数都以秒为单位返回自EPOCH (1970 年 1 月 1 日 00:00:00 UTC)以来的时间(时间是浮点数据类型)。由于该数字不像可理解的时间戳,我们必须转换该时间,即它变得可识别。为此,我们将使用时间库中的ctime()函数。
ctime(seconds)
Convert a time in seconds since the Epoch to a string in local time.
This is equivalent to asctime(localtime(seconds)). When the time tuple is
not present, current time as returned by localtime() is used.
Parameter:
seconds = A integer/float value
Return:
A string denoting a timestamp
下面是实现:
Python3
import os
import time
# Path to the file/directory
path = r"C:\Program Files (x86)\Google\pivpT.png"
# Both the variables would contain time
# elapsed since EPOCH in float
ti_c = os.path.getctime(path)
ti_m = os.path.getmtime(path)
# Converting the time in seconds to a timestamp
c_ti = time.ctime(ti_c)
m_ti = time.ctime(ti_m)
print(
f"The file located at the path {path}
was created at {c_ti} and was last modified at {m_ti}")
Python3
import os
import time
path = r"C:\Program Files (x86)\Google\pivpT.png"
ti_m = os.path.getmtime(path)
m_ti = time.ctime(ti_m)
# Using the timestamp string to create a
# time object/structure
t_obj = time.strptime(m_ti)
# Transforming the time object to a timestamp
# of ISO 8601 format
T_stamp = time.strftime("%Y-%m-%d %H:%M:%S", t_obj)
print(f"The file located at the path {path} was last modified at {T_stamp}")
输出:
The file located at the path C:\Program Files (x86)\Google\pivpT.png was created at Wed Dec 23 15:05:48 2020
and was last modified at Mon Dec 14 14:59:20 2020
上述代码的时间戳具有以下格式限定符 -
[Day](3) [Month](3) [day](2) [Hours:Minutes:Seconds](8) [Year](4)
括号内的单词是显示内容的提示,括号内跟在它后面的数字显示它将占用的长度。
注意:可以更改上述代码中使用的时间戳格式。默认情况下, ctime()函数将返回上述语法的时间戳。为了改变它,我们必须将它传递给strptime()函数(也可以在时间库中找到)以从中创建一个时间结构(对象)。然后我们可以将格式说明符传递给strftime() ,以根据时间结构创建自定义时间戳。在以下代码中,我们将以 ISO 8601 时间戳格式获取同一文件的修改时间。
蟒蛇3
import os
import time
path = r"C:\Program Files (x86)\Google\pivpT.png"
ti_m = os.path.getmtime(path)
m_ti = time.ctime(ti_m)
# Using the timestamp string to create a
# time object/structure
t_obj = time.strptime(m_ti)
# Transforming the time object to a timestamp
# of ISO 8601 format
T_stamp = time.strftime("%Y-%m-%d %H:%M:%S", t_obj)
print(f"The file located at the path {path} was last modified at {T_stamp}")
输出:
The file located at the path C:\Program Files (x86)\Google\pivpT.png was last modified at 2020-12-14 14:59:20