我想得到微秒,但最后三位数字始终为 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
因为这种方法最后给了我相同的零。
最佳答案
我认为这是 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)
在 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 似乎具有完整的微秒分辨率,因此您可能需要考虑切换到它(好像大量其他改进还不够)。
关于python - 日期时间中丢失的微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38841192/