Python fromtimestamp OSError [英] Python fromtimestamp OSError

查看:93
本文介绍了Python fromtimestamp OSError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,在使用 fromtimestamp 构建日期时间时,当我使用小于 -43200(-12 小时)的负时间时,我会收到OSError [Errno22] Invalid Argument".我在 Win7 64 位和 python 3.5.1 上.这是产生错误的代码.

<预><代码>>>>导入日期时间>>>进口pytz>>>datetime.datetime.fromtimestamp(-43200, pytz.utc)datetime.datetime(1969, 12, 31, 12, 0, tzinfo=<UTC>)>>>datetime.datetime.fromtimestamp(-43201, pytz.utc)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中OSError: [Errno 22] 无效参数

示例使用pytz来简化时区信息,但没有它也会出现错误.

解决方案

如果您收到此错误并且您没有使用明显错误的时间戳,请检查您的单位.

fromtimestamp 期望以秒为单位的时间戳,而以毫秒为单位获取时间戳是很常见的(例如,我在尝试解析日历小部件中 Moment.js 生成的时间戳时发现了这一点).

以时间戳 1523443804214 为例 - 这是 2018 年 4 月 11 日,大约在我发表这篇文章前 15 分钟.根据 Epoch Converter,没问题,但请注意:假设这个时间戳在毫秒:".

在 Python 中,这会返回一个 OSError:

In [15]: datetime.fromtimestamp(1523443804214.0)---------------------------------------------------------------------------OSError 回溯(最近一次调用最后一次)<ipython-input-15-0c8efd251031>在 <module>()---->1 datetime.fromtimestamp(1523443804214.0)

但是,如果我们除以一千:

In [17]: datetime.fromtimestamp(1523443804.214)Out[17]: datetime.datetime(2018, 4, 11, 11, 50, 4, 214000)

结果正是我们所期望的.

For some reason when constructing datetimes using fromtimestamp, I get a "OSError [Errno22] Invalid Argument" when I use negative times less than -43200 (-12hrs). I am on Win7 64-bit and python 3.5.1. Here's code that produces the error.

>>> import datetime
>>> import pytz
>>> datetime.datetime.fromtimestamp(-43200, pytz.utc)
datetime.datetime(1969, 12, 31, 12, 0, tzinfo=<UTC>)
>>> datetime.datetime.fromtimestamp(-43201, pytz.utc)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

The sample uses pytz to simplify timezone information, but the error also occurs without it.

解决方案

If you get this error and you're not using an obviously wrong timestamp, check your units.

fromtimestamp expects a timestamp in seconds, whereas it's quite common to get timetstamps in milliseconds (e.g. I found this when trying to parse a timestamp produced from Moment.js in a calendar widget).

Take the timestamp 1523443804214 - it's 11th April 2018, about 15 minutes before I made this post. According to Epoch Converter, no problem, but note: "Assuming that this timestamp is in milliseconds:".

In Python this returns an OSError:

In [15]: datetime.fromtimestamp(1523443804214.0)
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-15-0c8efd251031> in <module>()
----> 1 datetime.fromtimestamp(1523443804214.0)

However if we divide by a thousand:

In [17]: datetime.fromtimestamp(1523443804.214)
Out[17]: datetime.datetime(2018, 4, 11, 11, 50, 4, 214000)

the result is what we expect.

这篇关于Python fromtimestamp OSError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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