os.path.getmtime()我正在尝试使用并将时间转换为人类可读的格式来获取文件的修改日期;建议使用time.ctime()方法,但它也给出了日期和月份的名称,这是我不想要的。
可以格式化吗%d %m %Y, %H:%M?
目前我有这样的代码:
import os.path, time
path = #path of the file
print time.ctime(os.path.getmtime(path))
Run Code Online (Sandbox Code Playgroud)
您可以使用datetime.fromtimestamp()来做到这一点,例如:
file_time_string = dt.datetime.fromtimestamp(os.path.getmtime(__file__))
Run Code Online (Sandbox Code Playgroud)
import os
import datetime as dt
file_time = dt.datetime.fromtimestamp(os.path.getmtime(__file__))
print(file_time.strftime("%d %m %Y, %H:%M"))
Run Code Online (Sandbox Code Playgroud)
24 03 2018, 16:39
Run Code Online (Sandbox Code Playgroud)
如文档所述,该ctime函数仅调用asctime具有固定格式的 。如果您想使用strftime-style 格式字符串,方法是调用该strftime函数。
实际上有两种方法可以做到这一点。现代的方法是构造一个datetime对象并调用它的方法:
>>> datetime.datetime.fromtimestamp(mtime).strftime("%d %m %Y, %H:%M")
'21 03 2018, 20:34'
Run Code Online (Sandbox Code Playgroud)
如果您想坚持使用该time模块,则需要将其struct_tm传递给其函数:
>>> time.strftime("%d %m %Y, %H:%M", time.localtime(mtime))
'21 03 2018, 20:34'
Run Code Online (Sandbox Code Playgroud)
如果这是您对时间戳所做的唯一事情,则没有太大区别。但是,如果您希望能够对它们进行排序、对它们进行算术运算等,那么您可能会对datetime.