Published on 2015-06-27.
What is the precision of datetime in Python? The documentation says
Return the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, this may be possible on platforms supplying the C gettimeofday() function).
It goes on further to say
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second.
So, the answer is that it depends.
Let's try to figure out what it looks like on Windows using Python 3.4. For reference:
import sys
print(sys.version)
Let's create a series of datetime objects that we can analyze to find out how far apart they are:
import datetime
dates = []
for _ in range(10000000):
dates.append(datetime.datetime.now())
Let's load them into Pandas so we can analyze them:
import pandas as pd
date_series = pd.Series(dates)
date_series.head()
date_series.describe()
Let's remove all duplicates:
uniq_date_series = date_series.drop_duplicates()
uniq_date_series.describe()
Now let's figure out the delta between all uniqe dates:
deltas = uniq_date_series - uniq_date_series.shift(1)
deltas.describe()
And the smallest delta is
deltas.min()
This means that the smallest increment between two consecutive dates is 1ms. So we can not use the datetime on Windows to measure events that occur more frequently than 1ms.
And that is in the best case. This number will vary depending on how many other processes are running and what the Python code does in between two measurements.
What is Rickard working on and thinking about right now?
Every month I write a newsletter about just that. You will get updates about my current projects and thoughts about programming, and also get a chance to hit reply and interact with me. Subscribe to it below.