[英]How i can print the file creation date of various files in Python?
I'm trying to print the file date creation of various files.我正在尝试打印各种文件的文件日期创建。
So I've tried use this code:所以我试过使用这段代码:
import os
import datetime
pth = r"my_path"
def listDir(dir):
fileNames = os.listdir(dir)
for fileName in fileNames:
t = os.path.getctime(pth + str(\fileName));
print('Nombre: ' + fileName + t)
listDir(pth)
But, that don't works.但是,这行不通。 Another problem that i have is that i don't know how to put only in the date the
"Y/M/D"
characters.我遇到的另一个问题是我不知道如何只在日期中输入
"Y/M/D"
字符。
I appreciate your help.我感谢您的帮助。
I see a problem here.我在这里看到一个问题。
While using .getctime
the string you are passing is not a proper file-path.使用
.getctime
时,您传递的字符串不是正确的文件路径。 You are concatenating pth
with \filename
.您将
pth
与\filename
连接起来。 This syntactically worng.这在句法上磨损了。
You are missing the \
or other delimiter used in different os
for specifying directories.您缺少在不同
os
中用于指定目录的\
或其他分隔符。
You can try the below answer -您可以尝试以下答案 -
import os
import datetime
pth = r"my_path"
def listDir(dir):
fileNames = os.listdir(dir)
for fileName in fileNames:
file_path = os.path.join(pth, fileName)
ts = os.path.getctime(file_path) # this returns the creation timestamp.
dt = datetime.datetime.fromtimestamp(ts) # this converts the timestamp to datetime object.
print('Nombre: {0} --> {1}'.format(fileName ,dt.date())) # dt.date() will return only the date from the datetime object.
listDir(pth)
Notes:笔记:
Use os.path.join
for concatenating the paths as it takes care of which OS you are using.使用
os.path.join
连接路径,因为它负责您使用的操作系统。 We don't have to worry about /
or \\
or any other delimiter.我们不必担心
/
或\\
或任何其他分隔符。
Convert the date into datetime
object as manipulating and dealing
with datetime object will be much more easier than dealing with strings
.将日期转换为
datetime
时间 object 因为操作和dealing
日期时间 object 将比处理strings
容易得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.