Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: how do you concatenate time to a string?

Tags:

python

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>
like image 397
phill Avatar asked Aug 08 '11 18:08

phill


1 Answers

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)'
like image 125
phihag Avatar answered Sep 21 '22 02:09

phihag