python datetime fromtimestamp产生值错误年份超出范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31548132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:13:05  来源:igfitidea点击:

python datetime fromtimestamp yielding valueerror year out of range

pythondatetime

提问by Neil Hickman

When attempting to convert a float formatted timestamp e.g 1437506779950.0into a datetime object, I'm getting a ValueError "year is out of range".

当尝试将浮点格式的时间戳1437506779950.0转换为日期时间对象时,我收到 ValueError“年份超出范围”。

This code that I used, was working not 3 months ago. Revisiting it now, strangely is now throwing this error yet nothing in the code base has changed, only the data that is being passed to it, and the only data that has changed there is obviously the timestamp.

我使用的这段代码在 3 个月前还没有工作。现在重新审视它,奇怪的是现在抛出这个错误,但代码库中的任何内容都没有改变,只有传递给它的数据,并且唯一改变的数据显然是时间戳。

>>> f = 1437506779950.0
>>> datetime.datetime.fromtimestamp(float(f))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: year is out of range

I can't understand what would have changed to make this break?

我无法理解会发生什么变化才能打破这种局面?

采纳答案by sschilli

As noted in the answer for this question, this looks like a unit conversion issue. You have to divide your timestamp by 1000 to convert from milliseconds to seconds.

正如在这个问题的答案中所指出的,这看起来像是一个单位转换问题。您必须将时间戳除以 1000 才能将毫秒转换为秒。

If you want to preserve millisecond precision, instead divide by 1000.0.

如果要保留毫秒精度,请除以 1000.0。