36

如何获得自纪元以来的毫秒数?

请注意,我想要实际的毫秒数,而不是秒数乘以 1000。我正在比较时间少于一秒且需要毫秒精度的时间。(我看了很多答案,他们似乎都有* 1000)

我正在将我收到 POST 请求的时间与服务器上的结束时间进行比较。我只需要两次采用相同的格式,不管是什么。我认为 unix 时间会起作用,因为 Javascript 有一个函数来获取它

4

6 回答 6

30

time.time() * 1000 如果可能的话,会给你毫秒精度。

于 2013-08-11T05:42:22.770 回答
20

int(time.time() * 1000) will do what you want. time.time() generally returns a float value with double precision counting seconds since epoche, so multiplying it does no harm to the precision.

Another word to the misleading answer of @kqr: time.clock() does not give you the time of the epoch. It gives you the time that the process ran on the CPU for Unix, or the time passed since the first call to the function on Windows, see the python docs.

Also it's true that the docs state, that time.time() is not guaranteed to give you ms precision. Though this statement is mainly ment for you to make sure not to rely on this precision on embedded or praehistoric hardware, and I'm not aware of any example, where you actually wouldn't get ms precision.

于 2013-08-11T07:30:45.973 回答
15

我看到很多人建议time.time()。虽然time.time()是一种测量一天中实际时间的准确方法,但不能保证为您提供毫秒精度!从文档中:

请注意,尽管时间始终以浮点数形式返回,但并非所有系统都提供比 1 秒更好的时间精度。虽然此函数通常返回非递减值,但如果系统时钟已在两次调用之间调回,则它可以返回比先前调用更低的值。

不是两次比较时想要的程序!它可以以许多有趣的方式爆炸,而您却无法说出发生了什么。事实上,当比较两次时,您并不需要知道现在是什么时间,只要这两个值具有相同的起点即可。为此,该time库为您提供了另一个过程:time.clock(). 文档说:

在 Unix 上,以浮点数形式返回当前处理器时间,以秒为单位。精度,实际上是“处理器时间”含义的定义,取决于同名 C 函数的精度,但无论如何,这是用于对 Python 或计时算法进行基准测试的函数。

在 Windows 上,此函数根据 Win32 函数 QueryPerformanceCounter() 以浮点数形式返回自第一次调用此函数以来经过的挂钟秒数。分辨率通常优于一微秒

使用time.clock().


或者,如果您只是想测试代码运行的速度,您可以自己方便地使用它,并使用timeit.timeit()它为您完成所有测量,并且是测量代码执行时间的事实上的标准方法。

于 2013-08-11T09:15:25.700 回答
14

使用日期时间:

>>> import datetime
>>> delta = datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)
>>> delta
datetime.timedelta(15928, 52912, 55000)
>>> delta.total_seconds()
1376232112.055
>>> delta.days, delta.seconds, delta.microseconds
(15928, 52912, 55000)
于 2013-08-11T05:42:34.660 回答
2

Python 3.7 introduced time.time_ns() to finally solve this problem since time.time() as mentioned is not useful for this.

"returns time as an integer number of nanoseconds since the epoch."

https://www.python.org/dev/peps/pep-0564/
https://docs.python.org/3/library/time.html#time.time_ns

于 2020-01-15T10:14:40.367 回答
-4
import datetime
time = datetime.datetime.now()
ms = time.microsecond

Returns a 6 digit number, microsecond. The last 3 digits are useless in PC since it works with ticks, which is slower than microsecond. The first 3 digits should be enough for your need.

于 2013-08-11T05:45:17.357 回答