pythondatetimetimedstleap-second

Safest and most reliable way to measure short intervals in Python? (cross-platform, cross-hardware, resistant to DST and leap seconds)


The more I read about datetime arithmetic, the bigger a headache I get.

There's lots of different kinds of time:

And then the clocks can run faster or slower or jump backwards or forwards because of

And how these are dealt with depends in turn on:

So please can somebody tell me, for my specific use case, the safest and most reliable way to measure a short interval? Here is what I am doing:

I'm making a game in Python (3.7.x) and I need to keep track of how long it has been since certain events. For example, how long the player has been holding a button, or how long since an enemy has spotted the player, or how long since a level was loaded. Timescales should be accurate to the millisecond (nanoseconds are overkill).

Here are scenarios I want to be sure are averted:

And I can't really write tests for these since the problematic events come around so rarely. I need to get it right the first time. So, what time-related function do I need to use? I know there's plain old time.time(), but also a bewildering array of other options like

From reading the documentation it seems like time.monotonic() is the one I want. But if reading about all the details of timekeeping has taught me anything, it's that these things are never quite what they seem. Once upon a time, I thought I knew what a "second" was. Now I'm not so sure.

So, how do I make sure my game clocks work properly?


Solution

  • The specification of time module is the best place to look for details about each of those.

    There, you can easily see that:

    As for the nanoseconds versions, you should use those only if you need nanoseconds.