outputting time in microseconds or milliseconds

Ulrich Eckhardt ulrich.eckhardt at dominolaser.com
Fri Aug 2 07:59:30 EDT 2013


Am 02.08.2013 12:54, schrieb matt.doolittle33 at gmail.com:
> I am using 2.7 on Ubuntu 12.10.  All I need to do is to print time with the microseconds.[...]
>
>          #  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())))
>
> the output looks like this:
>
> 2013-08-02	06:01:43       00:00:00	
> 2013-08-02	06:01:43       00:00:00					
> 2013-08-02	06:01:43       00:00:00				
> 2013-08-02	06:01:43       00:00:00						
> 2013-08-02	06:01:43       00:00:00						

The output here and the code are surely not the same, provided that 
"time()" is the same as Python's "time.time()". That function will give 
you the time as a floating-point number and with as much precision as is 
available. You then only need the rest when dividing by one to get the 
fractional seconds.

BTW:
1. You have a race condition, you are retrieving the time thrice, which 
can and should yield different results for each call. Call it once, then 
format the results in multiple steps if you want.
2. Python's strftime() gives you a string already, calling str() on it 
is redundant. Also, formatting a string in order to then format it into 
another string is unnecessary overhead. Further, '%s' will implicitly 
invoke str() on the argument. Belt and suspenders anyone? :)

Good luck!

Uli





More information about the Python-list mailing list