Unix实时时间(以微秒为单位)python

时间:2018-10-09 06:26:41

标签: python python-3.x datetime time unix-timestamp

我尝试了以下操作并收到错误消息:

>>> datetime.utcfromtimestamp(1539065539).strftime('%Y-%m-%d %H:%M:%S.%f')
'2018-10-09 6:12:19.000000'.
>>> datetime.utcfromtimestamp(int(1539065539013987670)).strftime('%Y-%m-%d %H:%M:%S.%f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
>>> datetime.utcfromtimestamp(153906553901).strftime('%Y-%m-%d %H:%M:%S.%f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

我认为数字已经超出了int数据类型的大小。因此,此错误即将到来。我希望如何摆脱它并在毫秒内获得正确答案。

2 个答案:

答案 0 :(得分:2)

将值(实际上似乎是纳秒)除以1e9得到秒数,您可以将其传递给utcfromtimestamp

>>> datetime.datetime.utcfromtimestamp(1539065539013987670 / 1e9)
datetime.datetime(2018, 10, 9, 6, 12, 19, 13988)

答案 1 :(得分:1)

此问题在Python - Convert epoch time with nanoseconds to human-readable?

上回答
>>> datetime.utcfromtimestamp(1539065539013987670/1000000000).strftime('%Y-%m-%d %H:%M:%S.%f')
'2018-10-09 06:12:19.013988'