Reputation: 433
#!/usr/bin/python
import sys
import time
from time import time, sleep
end_time = time() + 3 * 3600
while time() < end_time:
with open('mytime.txt', 'a') as the_file:
the_file.write(time.strftime("%d.%m.%Y %H:%M:%S", time.localtime()))
sleep(60)
I am unable to print the current time to a file. My code leads to the following error:
Traceback (most recent call last):
File "./mytime.py", line 58, in <module>
the_file.write(time.strftime("%d.%m.%Y %H:%M:%S", time.localtime()))
AttributeError: 'builtin_function_or_method' object has no attribute 'strftime'
But this code works:
#!/usr/bin/python2
import time
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
However, it only prints the time and does not save it to a file.
Where is the difference, what do I make wrong in the first example?
Upvotes: 0
Views: 42
Reputation: 1078
In the first example you have:
from time import time
That means, if you call time.strftime(...)
, you tell Python to call strftime from object time
from module time
. Because you imported only object time
from module time
, not entire module. And the object time
is a function.
In the second example you import properly whole module:
import time
Upvotes: 1