Ski*_*man 26 python datetime timestamp
我需要一个自纪元以来毫秒(ms)的单个时间戳.这应该不难,我相信我只是缺少一些datetime类似的方法.
实际上,微秒(μs)粒度也很好.我只需要1/10秒的时间.
例.我有一个事件发生在每750毫秒,让我们说它检查灯是打开还是关闭.我需要记录每个检查和结果并稍后查看,以便我的日志需要如下所示:
...00250 Light is on
...01000 Light is off
...01750 Light is on
...02500 Light is on
Run Code Online (Sandbox Code Playgroud)
如果我只有完整的第二粒度,我的日志将如下所示:
...00 Light is on
...01 Light is off
...01 Light is on
...02 Light is on
Run Code Online (Sandbox Code Playgroud)
不够准确.
nmi*_*els 39
import time
time.time() * 1000
Run Code Online (Sandbox Code Playgroud)
其中1000是每秒毫秒.如果您想要的是自纪元以来的百分之一秒,则乘以100.
在Python中,datetime.now()可能会产生一个比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_micros = (now - epoch) // timedelta(microseconds=1)
posix_timestamp_millis = posix_timestamp_micros // 1000 # or `/ 1e3` for float
Run Code Online (Sandbox Code Playgroud)
从理论上讲,time.gmtime(0)(所用的时代time.time())可能与之不同1970.