Skip Huffman
Skip Huffman

Reputation: 5459

How can I create a Python timestamp with millisecond granularity?

I need a single timestamp of milliseconds (ms) since epoch. This should not be hard, I am sure I am just missing some method of datetime or something similar.

Actually microsecond (µs) granularity is fine too. I just need sub 1/10th second timing.

Example. I have an event that happens every 750 ms, lets say it checks to see if a light is on or off. I need to record each check and result and review it later so my log needs to look like this:

...00250 Light is on
...01000 Light is off
...01750 Light is on
...02500 Light is on

If I only have full second granularity my log would look like this:

...00 Light is on
...01 Light is off
...01 Light is on
...02 Light is on

Not accurate enough.

Upvotes: 45

Views: 104263

Answers (3)

Thomas Wagenaar
Thomas Wagenaar

Reputation: 6779

Note that although you can multiply time.time() with your desired degree of precision, it does not guarantee your device actually has that precision. For example, it has only +-1 ms precision on windows (source). For improved accuracy, use:

import time

now_ns = time.time_ns() # Time in nanoseconds
now_ms = int(now_ns / 1000000)

Only works from Python 3.7+

Upvotes: 4

jfs
jfs

Reputation: 414795

In Python, datetime.now() might produce a value with more precision than time.time():

from datetime import datetime, timezone, timedelta

now = datetime.now(timezone.utc)
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) # use POSIX epoch
posix_timestamp_millis = (now - epoch) // timedelta(milliseconds=1) # or `/ 1e3` for float

In theory, time.gmtime(0) (the epoch used by time.time()) may be different from 1970.

Upvotes: 14

nmichaels
nmichaels

Reputation: 51029

import time
time.time() * 1000

where 1000 is milliseconds per second. If all you want is hundredths of a second since the epoch, multiply by 100.

Upvotes: 69

Related Questions