undroid undroid - 1 month ago 4x
Python Question

Python - unable to use ctime to get last modified time

I'm learning Python (version 2.7.9 on win8) and currently going over the various

modules. I'm unable to get the last modified time of a file using
I'm facing this error:

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

Here are my imports:

import os
from os import path
from datetime import date,time, timedelta
from datetime import datetime


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


The error message is quite clear: datetime.time has no attribute 'ctime'. But the time module has a function ctime. You are shadowing the time module by the from datetime import time line.

>>> 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()