Python - 将纳秒的纪元时间转换为人类可读的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15649942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:37:40  来源:igfitidea点击:

Python - Convert epoch time with nanoseconds to human-readable?

pythontime

提问by victorhooi

I have a timestamp in epoch time with nanoseconds - e.g. 1360287003083988472nanoseconds since 1970-01-01.

我有一个以纳秒为单位的纪元时间戳 - 例如1360287003083988472自 1970-01-01 以来的纳秒。

The Python datetime objects and conversion methods only support up to millisecond precision.

Python 日期时间对象和转换方法仅支持最高毫秒精度。

Is there an easy way to convert this epoch time into human-readable time?

有没有一种简单的方法可以将这个纪元时间转换为人类可读的时间?

Cheers, Victor

干杯,维克多

采纳答案by Andrew Clark

First, convert it to a datetimeobject with second precision (floored, not rounded):

首先,将其转换为datetime具有第二精度的对象(落地,不四舍五入):

>>> from datetime import datetime
>>> dt = datetime.fromtimestamp(1360287003083988472 // 1000000000)
>>> dt
datetime.datetime(2013, 2, 7, 17, 30, 3)

Then to make it human-readable, use the strftime()method on the object you get back:

然后为了使其可读,请strftime()在您返回的对象上使用该方法:

>>> s = dt.strftime('%Y-%m-%d %H:%M:%S')
>>> s
'2013-02-07 17:30:03'

Finally, add back in the nanosecond precision:

最后,加回纳秒精度:

>>> s += '.' + str(int(1360287003083988472 % 1000000000)).zfill(9)
>>> s
'2013-02-07 17:30:03.083988472'

回答by abarnert

Actually, Python's datetimemethods handle microsecondprecision, not millisecond:

实际上,Python 的datetime方法处理微秒精度,而不是毫秒

>>> nanos = 1360287003083988472
>>> secs = nanos / 1e9
>>> dt = datetime.datetime.fromtimestamp(secs)
>>> dt.strftime('%Y-%m-%dT%H:%M:%S.%f')
'2013-02-07T17:30:03.083988'

But if you actually neednanoseconds, that still doesn't help. Your best bet is to write your own wrapper:

但是,如果您确实需要纳秒,那仍然无济于事。最好的办法是编写自己的包装器:

def format_my_nanos(nanos):
    dt = datetime.datetime.fromtimestamp(nanos / 1e9)
    return '{}{:03.0f}'.format(dt.strftime('%Y-%m-%dT%H:%M:%S.%f'), nanos % 1e3)

This gives me:

这给了我:

'2013-02-07T17:30:03.083988472'

Of course you could have done the same thing even if Python didn't do sub-second precision at all…

当然,即使 Python 根本没有达到亚秒级精度,您也可以做同样的事情……

def format_my_nanos(nanos):
    dt = datetime.datetime.fromtimestamp(nanos / 1e9)
    return '{}.{:09.0f}'.format(dt.strftime('%Y-%m-%dT%H:%M:%S'), nanos % 1e9)