Timestamp and microseconds on Windows platformsDaniele Esposti's Blog, in 12 July 2013
On both platforms, and at least with Python 2.7, the minimum resolution reported by
datetime is 1 microsecond:
datetime object returned by the datetime.now() function has a little difference between *nixes and Windows systems. On *nixes consecutive calls to
datetime.now() returns a sequence like this one:
where the last number is the microsecond part of the
datetime object. On Windows however the result is slightly different:
we still have microseconds but something is not right: the microseconds are multiple of 1000 which means the actual minimum resolution for a
datetime object returned by
datetime.now() is 1 millisecond.
This is not an issue if you are handling timestamps like the major of use cases where a timestamp is involved. In my case however I needed a timestamp which was unique and consecutive which is satisfied on *nix systems, the code is not fast enough to be run in less than 1 microsecond, but not in Windows systems where the code is obviously fast enough to be run in less than 1 millisecond, raising an exception because the timestamp wasn’t unique and consecutive.
I made a workaround to simulate the microsecond resolution even on Windows system by using a microseconds generator:
_usec_generator uses the itertools.cycle iterator to return a number in the range 0..999 to be used as fake microsecond value for the
datetime object. The generator will return an incremented number at every call adding the number to the current microsecond value.
Supposing I’m creating multiple Event instances in the same millisecond, the result will be:
As you can see now the microseconds starts with a 000 but increment at every
Event creation satisfying the requirement of an unique and consecutive timestamp.