Timestamp out of range for platform localtime()/gmtime() function

后端 未结 2 1751
隐瞒了意图╮
隐瞒了意图╮ 2020-12-11 03:44

I try:

ts = -216345600000
datetime.datetime.fromtimestamp(ts/1000)

ValueError: timestamp out of range for platform localtime()/gmti

2条回答
  •  情书的邮戳
    2020-12-11 04:17

    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'
    

    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 "", line 1, in 
        datetime(1970, 1, 1) + timedelta(seconds=253402300800)
    OverflowError: date value out of range
    

    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)
    

提交回复
热议问题