我是一个py新手,并想知道是否有一种更简单的方法将时间连接到写入函数中的字符串?这是我的代码运行带有activepy 2.6的windows xp:
from time import clock
filename = "c:\Python\\test.txt"
try:
tm = clock()
print "filename: " + filename
fsock = open(filename, "a")
try:
fsock.write(tm + 'test success\n ')
finally:
fsock.close()
except IOError:
print "file not found"
print file(filename).read()
Run Code Online (Sandbox Code Playgroud)
C:\Python>python test.py
filename: c:\Python\test.txt
Traceback (most recent call last):
File "test.py", line 8, in <module>
fsock.write(tm + 'test success\n ')
TypeError: unsupported operand type(s) for +: 'float' and 'str'
C:\Python>
Run Code Online (Sandbox Code Playgroud)
time.clock 返回系统运行持续时间的机器可读表示.
要获得当前墙上时间的人类可读表示(字符串),请使用time.strftime:
>>> import time
>>> tm = time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)')
>>> tm
'Mon, 08 Aug 2011 20:14:59 CEST(+0200)'
Run Code Online (Sandbox Code Playgroud)