python:如何将时间连接到字符串?

python:如何将时间连接到字符串?,python,Python,我是一个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")

我是一个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()

C:\Python>Python test.py
文件名:c:\Python\test.txt
回溯(最近一次呼叫最后一次):
文件“test.py”,第8行,在
fsock.write(tm+“测试成功\n”)
TypeError:不支持+:“float”和“str”的操作数类型
C:\Python>
使用蟒蛇


应首先使用str()将其转换为字符串:


最好使用string
format()
方法:

fsock.write({0}测试成功\n'.format(tm))

较老的方法是:

fsock.write(“%f测试成功\n%”(tm))

最后,您只需执行以下操作:


fsock.write(str(tm)+“test success\n”)

您可以使用格式字符串来包含任何浮点(如tm变量中的浮点)和如下字符串:

str = '%f test success\n' % tm
fsock.write(str)
我个人认为这是Python中最清晰、也是最灵活的字符串格式化方式。

返回系统运行时间的机器可读表示

要获取当前墙时间的可读表示形式(字符串),请使用:

fsock.write('{0} test success\n'.format(tm))
str(tm) + 'test success\n'
str = '%f test success\n' % tm
fsock.write(str)
>>> import time
>>> tm = time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)')
>>> tm
'Mon, 08 Aug 2011 20:14:59 CEST(+0200)'