【问题标题】:Microseconds lost in datetime日期时间丢失的微秒
【发布时间】:2016-12-14 22:28:07
【问题描述】:

我试图获得微秒,但最后三位数字始终为 0,所以我想我只能获得毫秒。 这是操作系统问题吗?我在 Win7x64 上使用 Python 2.7.10。 难道我做错了什么?否则我将如何获得微秒?

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 4, 33, 28, 504000)

这不是重复

Using %f with strftime() in Python to get microseconds

因为这种方法最后给了我相同的零。

【问题讨论】:

  • 可能是操作系统问题;在 LMDE Betsy (Linux) 64 位和 Python 2.7.9 上,我可以得到微秒:datetime.datetime(2016, 8, 9, 12, 46, 14, 209624)
  • 这是OS X 使用 Python 2.7.10 的输出:datetime.datetime(2016, 8, 8, 19, 49, 23, 952833)。在 Windoze 中,我得到 datetime.datetime(2016, 8, 8, 19, 49, 23, 952000)... 所以我会说 Fred 做到了。

标签: python datetime


【解决方案1】:

我认为这是 Windows 下 Python 2.7 实现的一个已知限制:

>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 50, 59, 657000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 1, 561000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 2, 314000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 2, 906000)
>>> datetime.datetime.now()
datetime.datetime(2016, 8, 9, 10, 51, 9, 277000)

例如,请参阅herehere

在Python 2.7源码中,函数Modules/datetimemodule.c/datetime_now()最终调用Modules/timemodule.c/floattime(),其注释如下:

/* There are three ways to get the time:
  (1) gettimeofday() -- resolution in microseconds
  (2) ftime() -- resolution in milliseconds
  (3) time() -- resolution in seconds
  In all cases the return value is a float in seconds.
  Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
  fail, so we fall back on ftime() or time().
  Note: clock resolution does not imply clock accuracy! */

因此,Windows 平台显然使用ftime() 来获取当前时间,并且根据the MSDN page for _ftime()(毫无疑问最终会出现),没有微秒可用。因此 Python 2.7 只为您提供毫秒数,而微秒数为零:

return (double)t.time + (double)t.millitm * (double)0.001;

Python 3.5 似乎具有完整的微秒分辨率,因此您可能需要考虑切换到该分辨率(好像大量的其他改进还不够)。

【讨论】:

  • 这不是一般 Windows 的限制,但可能是 Python 2.7 使用的 API 的限制。至少在 Windows 10 中,使用 Python 3.5.1,datetime.datetime.now() 正在为我填写微秒的低三位,例如>>> datetime.datetime.now(), datetime.datetime(2016, 8, 8, 23, 7, 13, 646615)
  • @Shadow,是的,与其说是 Windows 的限制,不如说是 Python 对 Windows API 的使用。编辑以正确分配责任:-)
  • @doc,这听起来像是一个新的 SO 问题的好标题。轻推眨眼眨眼。
  • 我读过一些关于 Python 3 在某些情况下速度较慢的内容,它似乎与我编写的代码相匹配。没有任何理由提出新问题。但是谢谢:)
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2011-10-18
  • 1970-01-01
  • 2016-02-14
  • 2021-09-03
  • 2023-04-04
  • 1970-01-01
相关资源
最近更新 更多