You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用time()函数触发OSError: [Errno 22]无效参数的原因排查

问题分析:OSError: [Errno 22] Invalid argument 在time.gmtime中的触发原因

问题重现

代码运行时抛出以下错误:

Traceback (most recent call last):
  File "C:\Users\School\Desktop\final countdown.py", line 7, in <module>
    y = str(getattr(time.gmtime(b - time.time()), 'tm_hour')), ':', str(
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 22] Invalid argument

涉及代码:

import time

if getattr(time.localtime(), 'tm_wday') == 2:
    a = time.strptime('2023-10-17 15:20:00', '%Y-%m-%d %H:%M:%S')
    b = int(time.mktime(a))
    while True:
        y = str(getattr(time.gmtime(b - time.time()), 'tm_hour')), ':', str(
            getattr(time.gmtime(b - time.time()), 'tm_min')), ':', str(getattr(time.gmtime(b - time.time()), 'tm_sec'))
        x = ''.join(y)
        print(x, end='\r')

原因解析

这个错误的核心原因是当前时间已经超过了目标时间2023-10-17 15:20:00,导致b - time.time()的结果为负数。

部分Python版本或系统环境下,time.gmtime()函数不支持处理1970年1月1日(Unix纪元)之前的时间戳(即负数值),传入负时间戳会直接抛出OSError: [Errno 22] Invalid argument。

之前代码能正常运行,是因为当时系统时间还没到2023-10-17 15:20:00,b - time.time()为正数,符合gmtime的参数要求。

解决方法

  1. 先判断当前时间是否未超过目标时间,仅在差值非负时执行倒计时逻辑
  2. 优化代码,避免重复调用gmtime(每次调用都会重新计算,浪费资源)

修改后的代码示例:

import time

target_time_str = '2023-10-17 15:20:00'
a = time.strptime(target_time_str, '%Y-%m-%d %H:%M:%S')
b = int(time.mktime(a))

# 仅在当前时间未超过目标时间时执行倒计时
if getattr(time.localtime(), 'tm_wday') == 2 and time.time() <= b:
    while True:
        remaining = b - time.time()
        # 检查剩余时间是否非负,避免触发错误
        if remaining < 0:
            print("倒计时已结束")
            break
        # 只调用一次gmtime,提升效率
        time_struct = time.gmtime(remaining)
        y = (str(time_struct.tm_hour), ':', str(time_struct.tm_min), ':', str(time_struct.tm_sec))
        x = ''.join(y)
        print(x, end='\r')
        # 添加短暂休眠,减少CPU占用
        time.sleep(0.1)
else:
    print("今日不是周三,或目标时间已过")

内容的提问来源于stack exchange,提问作者FireStorm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 13:35:03