gpt4 book ai didi

Python时间错误: mktime overflow

转载 作者:太空宇宙 更新时间:2023-11-03 16:05:38 24 4
gpt4 key购买 nike

使用 Python 时 time模块我收到此错误:

OverflowError: mktime argument out of range

我发现这个时间可能超出了纪元,因此无法在我的 Windows 环境中显示。

但是我测试的代码是:

import time
s = "20 3 59 3 "
t = time.mktime(time.strptime(s, "%d %H %M %S "))
print(t)

如何避免这种情况?我的目标是获得同一天不同时间点之间的差异。 (我不会得到任何有关月份或年份的信息)

最佳答案

您的问题是 time.strptime(s, "%d %H %M %S ") 创建的时间元组是:

(tm_year=1900, tm_mon=1, tm_mday=20, tm_hour=3, tm_min=59, tm_sec=3, tm_wday=5, tm_yday=20, tm_isdst=-1)

...以及 time.mktime() 的文档指出(强调我的):

time.mktime(t) This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC. It returns a floating point number, for compatibility with time(). If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform-dependent.

因此,这表明 1900 转换还为时过早。在我的系统(Win 7)上,我也收到错误,但如果我更改您的代码以包含最近一年:

>>> s = "1970 20 3 59 3 "
>>> t = time.mktime(time.strptime(s, "%Y %d %H %M %S "))
>>> print t
1655943.0

我没有收到任何错误,但如果我将年份更改为 1950,则会收到 OverflowError

因此,解决方案是在字符串中包含年份,time.mktime() 可以转换该年份。

关于Python时间错误: mktime overflow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39831460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com