【问题标题】:Issue with Python returning same timestamp several timesPython多次返回相同时间戳的问题
【发布时间】:2020-07-28 13:57:46
【问题描述】:

我正在使用一个 API,该 API 使用回调函数每秒最多发送 2000 次数据。函数的主体获取数据参数(API 调用函数使用),向其附加时间戳(使用 datetime.now().timestamp()),然后将其发送到队列,并将其保存在采集完成后的文件。

我面临的问题是我多次获得相同的时间戳,但数据不同。以下是一些已保存数据的示例:

数据-----时间戳

3258 1595943590.058758

3246 1595943590.058758

3246 1595943590.058758

3248 1595943590.058758

3254 1595943590.058758

3246 1595943590.058758

我尝试改用 time.time(),但问题仍然存在:

2986 1595944140.3182354

2986 1595944140.3182354

2984 1595944140.3182354

2984 1595944140.3182354

2984 1595944140.3182354

2986 1595944140.3182354

2986 1595944140.3182354

2982 1595944140.3182354

2980 1595944140.3182354

2986 1595944140.3182354

API 发送数据太快以至于时间更新不够快的问题?有没有更准确的获取时间的方法?

#part of a class
def apiFunc(self, data):
        if data:
                d = (data, time.time())
                self.storage.put(d)
                return True
        return False

【问题讨论】:

  • 你为什么认为这是一个问题?
  • @superbrain 因为我想要每个数据点的确切时间戳,以便以后同步和分析。

标签: python timestamp real-time


【解决方案1】:

也许将time.perf_counter 的精度与time.time 的意义相结合。这是代码和输出(左边是纯time.time,右边是我的建议):

>>> if 1:
    import time
    delta = time.time() - time.perf_counter()
    timestamps = []
    for _ in range(10):
        pure = time.time()
        mine = time.perf_counter() + delta
        timestamps.append((pure, mine))
    for row in timestamps:
        print(row)

(1595947258.0029619, 1595947258.0029738)
(1595947258.0029619, 1595947258.0029812)
(1595947258.0029619, 1595947258.0029826)
(1595947258.0029619, 1595947258.002984)
(1595947258.0029619, 1595947258.0029855)
(1595947258.0029619, 1595947258.0029874)
(1595947258.0029619, 1595947258.0029886)
(1595947258.0029619, 1595947258.00299)
(1595947258.0029619, 1595947258.0029914)
(1595947258.0029619, 1595947258.002993)

摘自更长的输出,其中纯时间最终发生了变化(不得不尝试数千行):

...
(1595947517.2481732, 1595947517.2532165)
(1595947517.2481732, 1595947517.2532175)
(1595947517.2481732, 1595947517.2532187)
(1595947517.256172, 1595947517.2532716)
(1595947517.256172, 1595947517.253275)
(1595947517.256172, 1595947517.253278)
...

【讨论】:

    【解决方案2】:

    根据this answer,Windows 上的time() 仅具有~16 毫秒的精度。

    标准 time.time() 函数提供亚秒级精度,但该精度因平台而异。对于 Linux 和 Mac,精度为 +- 1 微秒或 0.001 毫秒。由于进程中断导致的时钟实现问题,Windows 上的 Python 使用 +- 16 毫秒精度。如果您测量执行时间,timeit 模块可以提供更高的分辨率。

    【讨论】:

      猜你喜欢
      • 2017-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 2012-11-26
      • 1970-01-01
      • 2019-11-08
      • 2012-04-22
      相关资源
      最近更新 更多