Python无法使用ctime获取最后修改的tim

2024-10-03 17:28:08 发布

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

我正在学习Python(win8上的版本2.7.9),目前正在复习各种date和{}模块。我无法使用ctime获取文件的上次修改时间。 我面临这样的错误:

AttributeError: type object 'datetime.time' has no attribute 'ctime'

以下是我的进口:

^{pr2}$

脚本:

modTime = time.ctime(os.path.getmtime("t.txt"))
print "t.txt was last modified at: " + modTime # This Doesn't work 

print datetime.fromtimestamp(path.getmtime("t.txt")) # This works

Tags: 模块文件path版本txtdatetimedatetime
3条回答

其他答案是正确的,但是它们没有给您提供关于如何使用imports的好建议,即不要使用“from”,而是使用完全限定的名称,如PEP8

It's much better to:

  • reference names through their module (fully qualified identifiers),
  • import a long module using a shorter name (alias; recommended),
  • or explicitly import just the names you need.

我遵循1或2,从不遵循3,原因正是你的程序不起作用:

import os
import time

modTime = time.ctime(os.path.getmtime("t.txt"))
print "t.txt was last modified at: " + modTime # This works now! 

例如#2是:

^{pr2}$

因此time.表示来自time模块的内容,dt_time是函数{},并且消除了名称歧义。在

毫无疑问,人们会不同意这是过于迂腐,但它确实使你远离进口麻烦。在

以下是您的更正进口:

import os
from os import path
import time
from datetime import datetime

错误信息非常清楚:datetime.time has no attribute 'ctime'。但是time模块有一个函数ctime。您正在通过from datetime import time行跟踪time模块。在

>>> import time
>>> time  # refers to the *module*
<module 'time' from '/usr/lib/python2.7/lib-dynload/time.so'>
>>> time.ctime()
'Sun Feb  1 16:23:33 2015'
>>> from datetime import time
>>> time  # now we have a class of that name
<type 'datetime.time'>
>>> t = time()
>>> t.isoformat()
'00:00:00'

相关问题 更多 >