无法将Epoch值转换为人类可读的日期格式python

时间:2019-08-30 13:55:03

标签: python python-3.x

我正在尝试使用Python版本3转换纪元值-2208988800000

我尝试了在线工具来转换https://www.epochconverter.com/,所以我得到的输出为1900年1月1日。

import datetime
datetime.datetime.fromtimestamp(-2208988800000 / 1000).strftime('%c')

---------------------------------------------------------------------------
OSError
Traceback (most recent call last)
  <ipython-input-15-abaf34dc5003> in <module>()
----> 1 datetime.datetime.fromtimestamp(-2208988800000 / 1000).strftime('%c')

OSError: [Errno 22] Invalid argument

2 个答案:

答案 0 :(得分:2)

fromtimestamp的行为取决于平台。我在Windows 10上,并且不支持负值。

摘录自the documentation

  如果时间戳超出平台C localtime()或gmtime()函数支持的值范围,则

fromtimestamp()可能会引发ValueError。通常将其限制在1970年到2038年之间。

>>> from datetime import datetime as dt
>>> dt.fromtimestamp(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

答案 1 :(得分:1)

我无法复制您的问题;我在Python 3.6上使用Ubuntu 18.04并得到以下输出(由于时区的原因可能会略有不同):

>>> import datetime
>>> datetime.datetime.fromtimestamp(-2208988800000 / 1000).strftime('%c')
'Sun Dec 31 20:09:20 1899'
>>> datetime.datetime.fromtimestamp(-2208988800000 / 1000)
datetime.datetime(1899, 12, 31, 20, 9, 20)

并使用您在问题中提到的转换器,这似乎是正确的:

screenshot


fromtimestamp() docs说任何OSError来自time.localtime()