平台localtime()/ gmtime()函数的时间戳超出范围 [英] Timestamp out of range for platform localtime()/gmtime() function

查看:421
本文介绍了平台localtime()/ gmtime()函数的时间戳超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试:

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

ValueError:平台localtime()/ gmtime()函数的时间戳超出范围

我检查 epochconverter 值:-216345600返回GMT:1963年2月23日星期六,格林尼治标准时间

I check on epochconverter value : -216345600 its return GMT: Sat, 23 Feb 1963 00:00:00 GMT

如何获取正确的结果?

推荐答案

对于许多值,例如过去或将来的值太远,仅将时间戳从timestamp()馈入 就会抱怨超出范围错误。但是,您可以使用 timedelta()来计算日期 相对于纪元。

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'

但是,请注意,由于 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()也有其限制,但以纪元为参考点,我们甚至还没有达到极限。

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)

这篇关于平台localtime()/ gmtime()函数的时间戳超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆