首页 > 解决方案 > 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

我知道它可能很愚蠢或很小,但我就是看不到发生了什么,有人有什么想法吗?

标签: pythonpython-3.x

解决方案


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

推荐阅读