如何将 datetime 对象转换为 time_ns
我有以下问题我需要将一些日期时间对象转换为 time_ns (存在于时间中)
我能找到的就是将现在的日期时间转换为固定的纳秒数(我知道它是根据 1970 年的固定日期计算的)
import time
now = time.time_ns()
我所有想要的是将一些正常的日期时间对象转换为固定的纳秒数,
from datetime import datetime
x = datetime(2022, 2, 22, 15, 41, 50)
我不想仅限于现在的日期。库中有一些函数可以做到这一点吗?目前我找不到任何东西,
非常感谢
I have the following problem I need to convert some datetime object to time_ns (present in time)
all I can find is to convert the now datetime to that fixed nanoseconds number (i understand that it is calculated from a fixed date in 1970)
import time
now = time.time_ns()
all I want is to convert some normal datetime object to that fixed nanoseconds number
from datetime import datetime
x = datetime(2022, 2, 22, 15, 41, 50)
i don't want to be restricted to only now dates. is there some function in the library that does that? for the moment i cannot find anything
thank you very much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从python 3.3开始,datetime有了时间戳函数。确保替换时区,否则将采用本地时区,如果您想要纳秒数,可以乘以秒数。
Since python 3.3 datetime has a timestamp function. Make sure to replace the timezone, otherwise local timezone will being taken and if you want to have nanosecond number you can multiply the seconds number.
请注意,如果您只是尝试将
time.time()
或time.time_ns()
转换为日期和时间,请使用time.localtime( )
或time.gmtime()
。请参阅此处每个函数的各种参考文档说明: https:// /docs.python.org/3/library/time.html#time.time:
示例:
这都是我在这里的更大答案:Python 中的高精度时钟
Note that if you're just trying to convert
time.time()
ortime.time_ns()
into a date and time instead, usetime.localtime()
ortime.gmtime()
.See the various reference documentation descriptions for each of those functions here: https://docs.python.org/3/library/time.html#time.time:
Examples:
That's all from my bigger answer here: High-precision clock in Python