开发者

python: how do you concatenate time to a string?

I'm a py newbie and was wondering if there was a simpler way to concatenate time to a string in a write function? here is my code running windows xp with activepy 2.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>


time.clock returns a machine-readable representation of the duration the system is running.

To get a human-readable representation (a string) of the current wall time, use 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)'


Use pythons str.format

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


You should convert to string first using str():

str(tm) + 'test success\n'


The best thing to do would be to use the string format() method:

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

The older way of doing this would be:

fsock.write('%f test success\n'%(tm))

Finally, you can just do:

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


You can use format strings to include any float (like the one you have in the tm variable) and a string like so:

str = '%f test success\n' % tm
fsock.write(str)

I personally find this to be the clearest and yet most flexible way of string formatting in Python.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜