python - 日期时间中丢失的微秒

标签 python datetime

我想得到微秒,但最后三位数字始终为 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)

参见,例如,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 似乎具有完整的微秒分辨率,因此您可能需要考虑切换到它(好像大量其他改进还不够)。

关于python - 日期时间中丢失的微秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38841192/

相关文章:

SQL 选择特定日期格式 dd/mm/YYYY hh :mm:ss

python - 在 Python 中安装本地附加功能

python - 使用列表作为 Python 字典中的键

python - 在列表中打印 Unicode 字符

python - 从 Eclipse 运行时关闭 matplotlib 中预先存在的图形

python - pandas 按分钟比较时区感知日期时间字段

python - 使用 PIL 检测图像是否有边框

python - 获取具有日期时间格式的列,例如 (2017-02-12 10 :23:55 AM)[YYYY-MM-dd hh:mm:ss AM/PM] using pandas

apache-spark - 如何将不同的时区应用于 PySpark 中的时间戳

javascript - 在 codeigniter 中查找数据库中的两个日期时间差异