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

问题描述 投票:0回答:2

我对此有点困惑,我不会撒谎,但目前每次我尝试将 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

我知道这可能是一些愚蠢或小事,但我只是看不出发生了什么,有人有任何想法吗?

python python-3.x
2个回答
1
投票

epch 时间不包括毫秒,因此目前只有 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 位代表毫秒。以下是日期时间模块的摘录

@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

0
投票

如果您有机会该值可以以秒和毫秒为单位,我建议您这样做:

from datetime import datetime


def check(time_stamp):
    match len(str(time_stamp)):
        case 10:
            print(time_stamp, 'seconds')
            print(datetime.fromtimestamp(time_stamp))
        case 13:
            print(time_stamp, 'milliseconds')
            print(datetime.fromtimestamp(time_stamp / 1000))

check(1725062400000)
check(1725062400)

结果:

1725062400000 毫秒

2024-08-31 05:00:00

1725062400秒

2024-08-31 05:00:00

© www.soinside.com 2019 - 2024. All rights reserved.