Python:如何将时间附加到字符串?

7 投票
5 回答
24577 浏览
提问于 2025-04-16 23:08

我刚开始学Python,想知道有没有更简单的方法可以在写入函数中把时间加到字符串里?这是我在Windows XP上用ActivePython 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>

5 个回答

3

你应该先用 str() 把它转换成字符串:

str(tm) + 'test success\n'
7

使用Python的 str.format 方法

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

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

撰写回答