問題描述
我試試:
ts = -216345600000
datetime.datetime.fromtimestamp(ts/1000)
ValueError:平臺(tái) localtime()/gmtime() 函數(shù)的時(shí)間戳超出范圍
我檢查 epochconverter 值:-216345600 其返回 GMT:星期六,1963 年 2 月 23 日 00:00:格林威治標(biāo)準(zhǔn)時(shí)間 00
I check on epochconverter value : -216345600 its return GMT: Sat, 23 Feb 1963 00:00:00 GMT
如何得到正確的結(jié)果?
推薦答案
對(duì)于許多值,比如過去或未來太遠(yuǎn),只需將時(shí)間戳提供給 fromtimestamp()
就會(huì)報(bào)錯(cuò)超出范圍錯(cuò)誤.但是,您可以使用 timedelta()
相對(duì)于時(shí)代.
For many values, like too far in the past or the future, just feeding the timestamp to fromtimestamp()
will complain with an out of range error. However, you can calculate the date using timedelta()
relative from the epoch.
>>> from datetime import datetime, timedelta
>>> date = datetime(1970, 1, 1) + timedelta(seconds=-216345600)
>>> date
datetime.datetime(1963, 2, 23, 0, 0)
>>> date.strftime('%a, %d %b %Y %H:%M:%S GMT')
'Sat, 23 Feb 1963 00:00:00 GMT'
但是,請(qǐng)注意,您不能使用它來回到恐龍時(shí)代,因?yàn)?datetime()
仍然有它可以支持的最小值和最大值.
However, do note that you can't use this to go back to the dinosaur era, since datetime()
still has a min and max value it can support.
>>> datetime(1970, 1, 1) + timedelta(seconds=-62135596800)
datetime.datetime(1, 1, 1, 0, 0)
>>> datetime(1970, 1, 1) + timedelta(seconds=253402300799)
datetime.datetime(9999, 12, 31, 23, 59, 59)
>>> datetime(1970, 1, 1) + timedelta(seconds=253402300800)
Traceback (most recent call last):
File "<pyshell#157>", line 1, in <module>
datetime(1970, 1, 1) + timedelta(seconds=253402300800)
OverflowError: date value out of range
timedelta()
也有其局限性,但以時(shí)代為參考點(diǎn),我們甚至還沒有達(dá)到.
timedelta()
has its limits as well, but with the epoch as a reference point, we haven't come even near reaching them.
>>> timedelta(microseconds=1000000000*86400*10000-1)
datetime.timedelta(9999999, 86399, 999999)
這篇關(guān)于平臺(tái) localtime()/gmtime() 函數(shù)的時(shí)間戳超出范圍的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!