[英]python: how do you concatenate time to a string?
我是一個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
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>
fsock.write('{0} test success\n'.format(tm))
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)'
您應該首先使用str()轉換為字符串:
str(tm) + 'test success\n'
最好的辦法是使用字符串format()
方法:
fsock.write('{0} test success\\n'.format(tm))
較舊的方法是:
fsock.write('%f test success\\n'%(tm))
最后,您可以這樣做:
fsock.write(str(tm) + 'test success\\n')
你可以使用格式字符串來包含任何浮點數(就像你在tm變量中那樣)和一個像這樣的字符串:
str = '%f test success\n' % tm
fsock.write(str)
我個人認為這是Python中最清晰,最靈活的字符串格式化方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.