outputting time in microseconds or milliseconds

Roy Smith roy at panix.com
Sun Aug 4 10:33:48 EDT 2013


In article <07f6b1c7-069d-458b-a9fe-ff30c09f2f2d at googlegroups.com>,
 matt.doolittle33 at gmail.com wrote:

> self.logfile.write('%s\t'%(str(time())))
> [...]
> 1375588774.89
> [...]
> Why is it only giving me the centisecond precision?  the docs say i should 
> get microsecond precision

When citing documentation, it's a good idea to provide a link to the 
docs page, and/or a direct quote of what you read.

I'm looking at http://docs.python.org/2/library/time.html#time.time, 
which says, "not all systems provide time with a better precision than 1 
second".  So, I don't know where you got the impression that you're 
guaranteed microsecond precision.

Earlier in the thread, you did mention that you're on Ubuntu, and there 
you do indeed get pretty good precision.  I'm not 100% sure if it's good 
to the microsecond (it appears to be), but it's certainly better than 
centisecond.

Anyway, your problem appears to be that str(float) gives you two digits 
after the decimal (at least for values in the range we're talking about 
here), but repr() will give you more:

>>> t = time.time()
>>> str(t)
'1375626035.26'
>>> repr(t)
'1375626035.260934'

I don't know anywhere that those behaviors are guaranteed, however.  If 
you want to make sure you print a float with 6 digits after the decimal, 
you should use %f, not %s:

>>> '%.6f' % t
'1375626035.260934'

Of course, if the underlying system call that time.time() invokes 
returns less precision than microseconds, some of those 6 digits may 
always be zero.  Or worse, garbage.

Taking a step back, you're probably better off using datetimes.  You'll 
get all this conversion nonsense for free:

>>> print datetime.datetime.utcnow()
2013-08-04 14:33:09.255096

When I write an operating system, I'm going to have it keep time in 
units of YiTp (Yobi Plank times).



More information about the Python-list mailing list