【问题标题】:Nanoseconds exhibit strange behaviour纳秒表现出奇怪的行为
【发布时间】:2021-04-26 18:18:52
【问题描述】:

我有以下目标:在 python 中将日期时间字符串转换为纳秒整数。

这是我在这个过程中发现的奇怪之处:

from datetime import datetime

datetime_str = '2015-01-08T08:23:21.301812Z'

nanoseconds = 1000000000
datetime_nanoseconds = int(datetime.strptime(datetime_str, '%Y-%m-%dT%H:%M:%S.%fZ').timestamp() * nanoseconds)

当我打印datetime_nanoseconds 时,我得到以下号码1420701801301811968。

第一个问题:最后三个数字968是从哪里来的?我期待1420701801301812000

令人惊讶的是,如果我将 1420701801301811968 / nanoseconds 除以我期望的值 1420701801.301812 以秒为单位,而这最后三位数字现在消失了。

第二个问题:为什么最后三位数字现在消失了?

我觉得 python 不适合处理亚微秒时间...

非常感谢您对此主题的任何帮助。

【问题讨论】:

    标签: python datetime time


    【解决方案1】:

    datetime.timestamp() 返回一个浮点值。与 Python 的整数不同,浮点值没有无限精度。双精度浮点数大约有 17 位精度,而您已经超过了。所以,不要使用timestamp()。取timestamp()的整数值,乘以1000000,加上microsecond的值,再乘以1000。

    【讨论】:

    • 听起来合法。 .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多