How can I create a Python timestamp with millisecond granularity?

82,422

Solution 1

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.

Solution 2

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.

Share:
82,422
Skip Huffman
Author by

Skip Huffman

I am a Senior Software Engineer in Test. Or maybe a Senior Software Developer in Test. Perhaps a Senior Developer in Test. Could it be a Senior Software Development Engineer in Test. Argh. I build robots in software to break other software. In the computer industry since 1989. Mostly QA, Customer Support, and Documentation. Secondary programmer. I have worked extensively with Forth, Rexx, Perl, and for the past few years, Python.

Updated on February 03, 2022

Comments

  • Skip Huffman
    Skip Huffman about 2 years

    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.

  • bgporter
    bgporter about 13 years
    ..or int((time.time() + 0.5) * 1000) to get it as the nearest integral number of ms.
  • nmichaels
    nmichaels about 13 years
    @bgporter: Or int(round(time.time() * 1000)).
  • Skip Huffman
    Skip Huffman about 13 years
    ok, so time.time() is giving me decimal seconds with a 1/100 granularity. That will do.
  • Skip Huffman
    Skip Huffman about 13 years
    Well, except that I need to pull it out of exponential notation
  • nmichaels
    nmichaels about 13 years
    @Skip: int(round(time.time() * 1000)) gives me 1300819189007. Are you doing something weird with it?
  • Skip Huffman
    Skip Huffman about 13 years
    Ah, the round is what I needed. Thanks
  • Tom Chapin
    Tom Chapin over 6 years
    To get your code to work, I add to add datetime.datetime to the calls
  • jfs
    jfs over 6 years
    @TomChapin wrong. The code in the answer works as is. Look at the import in the very first line in the code.