outputting time in microseconds or milliseconds

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 2 08:35:13 EDT 2013


On Fri, 02 Aug 2013 03:54:32 -0700, matt.doolittle33 wrote:

> Hey everybody,
> 
> I am using 2.7 on Ubuntu 12.10.  All I need to do is to print time with
> the microseconds.  I have been looking at the docs and trying things for
> about half a day now with no success.  Currently my code looks like
> this:
> 
>         #  write date and time and microseocnds
>         self.logfile.write('%s\t'%(str(strftime("%Y-%m-%d", ))))
>         self.logfile.write('%s\t'%(str(strftime("%H:%M:%S", ))))
>         self.logfile.write('%s\t'%(str(time())))

What's this time() function? Where does it come from, and what does it 
do? By the look of it, it merely returns the string "00:00:00". The 
time.time() function returns a number of seconds:

py> "%s" % time.time()
'1375445812.873546'

so I'm not sure what function you are calling there.

Also, you don't need to call str() before using the %s template, since 
that automatically converts any object to a string. Besides, 
time.strftime already returns a string.

You can replace all of those above lines with a single format string:

py> import time
py> print(time.strftime("%Y-%m-%d\t%H:%M:%S"))
2013-08-02      22:31:14


If you google for "strftime millisecond" with the search engine of your 
choice:

https://duckduckgo.com/?q=strftime%20millisecond


you will find this bug report:

http://bugs.python.org/issue1982


Unfortunately, the %S.%f codes do not appear to work for me on Linux 
using Python 2.6, 2.7 or 3.3. Perhaps you will have better luck.


-- 
Steven



More information about the Python-list mailing list