Error22-简单的日期时间转换中的无效参数?

时间:2020-03-04 09:05:27

标签: python python-3.x

对此我感到很困惑,我不会说谎,但是每次我尝试将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

我知道它可能有点愚蠢或很小,但我只是看不到发生了什么,有人有什么主意吗?

1 个答案:

答案 0 :(得分:1)

eopch时间将不包括毫秒,因此当前只有10位数字长。您的年满13岁,可以通过将下限除以1000来摆脱多余的毫秒数

array:4 [▼
  "default" => "mysql"
  "connections" => array:4 [▼
    "sqlite" => array:5 [▶]
    "mysql" => array:15 [▼
      "driver" => "mysql"
      "url" => null
      "host" => "127.0.0.1"
      "port" => "3306"
      "database" => "geeknews"
      "username" => "root"
      "password" => ""
      "unix_socket" => ""
      "charset" => "utf8mb4"
      "collation" => "utf8mb4_unicode_ci"
      "prefix" => ""
      "prefix_indexes" => true
      "strict" => true
      "engine" => null
      "options" => []
    ]
    "pgsql" => array:12 [▶]
    "sqlsrv" => array:10 [▶]
  ]
  "migrations" => "migrations"
  "redis" => array:4 [▶]
]

输出

from datetime import datetime
msgTime = 1540406475702
print (msgTime)
messageTime=datetime.utcfromtimestamp(msgTime//1000)
print(messageTime)

更新

已经查看了datetime的源代码以及它如何实现timetimestamp(如果要传递毫秒),则可以通过将值传递为浮点数来实现,其中小数点后的3位数字代表毫秒。下面是datetime模块的摘录

1540406475702
2018-10-24 18:41:15

因此,如果您将毫秒/微秒作为小数点后的数字传递,则可以传递毫秒/微秒。

在您的纪元第二秒之后是小数位然后是毫秒之前,这是否可行?

@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)