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

2024-05-23 20:37:11 发布

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

我是一个py新手,想知道是否有一种更简单的方法将时间连接到write函数中的字符串?下面是我运行WindowsXP和ActivePy2.6的代码:

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

Tags: 方法pytesttxt时间filenamefilewrite
3条回答

您应该首先使用str()转换为字符串:

str(tm) + 'test success\n'

使用Pythonstr.format

fsock.write('{0} test success\n'.format(tm))

^{}返回系统运行持续时间的机器可读表示。

要获取当前墙时间的可读表示(字符串),请使用^{}

>>> import time
>>> tm = time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)')
>>> tm
'Mon, 08 Aug 2011 20:14:59 CEST(+0200)'

相关问题 更多 >