在 Python 中以秒和纳秒为单位获取 POSIX/Unix 时间? [英] Get POSIX/Unix time in seconds and nanoseconds in Python?
问题描述
自 1970-01-01 00:00:00 UTC 以来,我一直在尝试寻找一种方法,以秒和纳秒为单位在 python 中获取时间,但我找不到任何可以给我适当精度的东西.
I've been trying to find a way to get the time since 1970-01-01 00:00:00 UTC in seconds and nanoseconds in python and I cannot find anything that will give me the proper precision.
我试过使用时间模块,但精度只有微秒,所以我尝试的代码是:
I have tried using time module, but that precision is only to microseconds, so the code I tried was:
import time
print time.time()
这给了我这样的结果:
1267918039.01
但是,我需要一个看起来像这样的结果:
However, I need a result that looks like this:
1267918039.331291406
有谁知道以秒和纳秒表示 UNIX 时间的可能方法?我找不到设置正确精度或以正确格式获得结果的方法.感谢您的帮助
Does anyone know a possible way to express UNIX time in seconds and nanoseconds? I cannot find a way to set the proper precision or get a result in the correct format. Thank you for any help
推荐答案
从 Python 3.7 开始,使用 time.time_ns()
Since Python 3.7 it's easy to achieve with time.time_ns()
与 time()
类似,但以自纪元以来的纳秒整数形式返回时间.
Similar to
time()
but returns time as an integer number of nanoseconds since the epoch.
在 Python 3.7 版本中包含纳秒的所有新功能:PEP 564:添加具有纳秒分辨率的新时间函数
All new features that includes nanoseconds in Python 3.7 release: PEP 564: Add new time functions with nanosecond resolution
这篇关于在 Python 中以秒和纳秒为单位获取 POSIX/Unix 时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!