python - Error22 - 简单日期时间转换的参数无效?
问题描述
我对此有点难过,我不会撒谎,但我目前每次尝试将 13 个字符的纪元转换为可读日期时都会抛出一个无效的参数错误。这在脚本的早期工作没有问题,错误的部分如下:
print (msgTime)
messageTime=datetime.utcfromtimestamp(msgTime)
'msgTime' 的值是从 SQL 数据库中收集的,并返回为:1540406475702
我得到的确切错误是:
Traceback (most recent call last):
File "script.py", line 380, in <module>
messageTime=datetime.utcfromtimestamp(msgTime)
OSError: [Errno 22] Invalid argument
我知道它可能很愚蠢或很小,但我就是看不到发生了什么,有人有什么想法吗?
解决方案
eopch 时间不包括毫秒,因此目前只有 10 位数长。你是 13,你可以通过除以 1000 来消除额外的毫秒
from datetime import datetime
msgTime = 1540406475702
print (msgTime)
messageTime=datetime.utcfromtimestamp(msgTime//1000)
print(messageTime)
输出
1540406475702
2018-10-24 18:41:15
更新
查看了 datetime 的源代码以及它如何实现 fromtimestamp 如果您想传递毫秒,您可以通过将值作为浮点数传递来实现,其中小数点后的 3 位数字表示毫秒。以下是 datetime 模块的摘录
@classmethod def _fromtimestamp(cls, t, utc, tz): """Construct a datetime from a POSIX timestamp (like time.time()). A timezone info object may be passed in as well. """ frac, t = _math.modf(t) us = round(frac * 1e6) if us >= 1000000: t += 1 us -= 1000000 elif us < 0: t -= 1 us += 1000000 converter = _time.gmtime if utc else _time.localtime y, m, d, hh, mm, ss, weekday, jday, dst = converter(t) ss = min(ss, 59) # clamp out leap seconds if the platform has them result = cls(y, m, d, hh, mm, ss, us, tz)
因此,如果您将它们作为小数点后的数字传递,则可以传递毫秒/微秒。是否有可能在您的时代是第二个后跟小数位然后是毫秒之前工作?
from datetime import datetime
msgTime = 1540406475.702
print (msgTime)
messageTime=datetime.utcfromtimestamp(msgTime)
print(messageTime)
输出
1540406475.702
2018-10-24 18:41:15.702000
推荐阅读
- c# - 从 CSV 文件中读取并将其内容“保存”到 List 对象并将它们加载到 Program.cs
- javascript - Duktape - 评估时 for of 循环出错
- django - 基于 django 类的 CreateApiView author_id 不为空?
- java - 如何使用 API Stream 处理 ZonedDateTime?
- javascript - Loopback 3 和 REST API 标头的挂钩
- python - 我的 Python 线程启动但不执行任何操作(已修复)
- algorithm - 有没有更好的方法在 Dart 中编写这个函数
- reactjs - 我可以从 Material UI 创建自定义组件库 NPM 包吗?
- reactjs - Material UI 中的类名不正确,反应框架内的样式组件
- google-cloud-platform - 为本地 Strapi 应用程序连接到 Google Cloud PostgresSQL Server