doc doc - 1 year ago 109
Python Question

Microseconds lost in datetime

I'm trying to get microseconds but the last three digits always are 0, so I suppose I only can get milliseconds.
Is this an OS issue? I'm on Win7x64 with Python 2.7.10.
Am I doing something wrong? How else would I get microseconds?

>>> import datetime
datetime.datetime(2016, 8, 9, 4, 33, 28, 504000)

This is not a duplicate of

Using %f with strftime() in Python to get microseconds

as this approach gives me the same zeroes at the end.

Answer Source

I believe that's a known limitation of the Python 2.7 implementation under Windows:

>>> import datetime
datetime.datetime(2016, 8, 9, 10, 50, 59, 657000)
datetime.datetime(2016, 8, 9, 10, 51, 1, 561000)
datetime.datetime(2016, 8, 9, 10, 51, 2, 314000)
datetime.datetime(2016, 8, 9, 10, 51, 2, 906000)
datetime.datetime(2016, 8, 9, 10, 51, 9, 277000)

See, for example, here and here.

In the Python 2.7 source code, the function Modules/datetimemodule.c/datetime_now() eventually calls Modules/timemodule.c/floattime(), which has the following comment:

/* There are three ways to get the time:
  (1) gettimeofday() -- resolution in microseconds
  (2) ftime() -- resolution in milliseconds
  (3) time() -- resolution in seconds
  In all cases the return value is a float in seconds.
  Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  fail, so we fall back on ftime() or time().
  Note: clock resolution does not imply clock accuracy! */

So the Windows platform is obviously using ftime() to get the current time and, as per the MSDN page for _ftime() (which it no doubt ends up in), no microseconds are available. Therefore Python 2.7 just gives you the milliseconds and leaves the microseconds as zero:

return (double)t.time + (double)t.millitm * (double)0.001;

Python 3.5 appears to have a full microsecond resolution so you may want to consider switching to that (as if the large number of other improvements weren't enough).