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

如何解决pywin32与PyInstaller打包时的AttributeError错误?

解决PyInstaller打包pywin32代码时出现的AttributeError: 'pywintypes.datetime' object has no attribute 'astimezone'问题

这个错误通常是因为PyInstaller打包过程中没有正确包含pywin32库的全部依赖,导致运行时pywintypes.datetime对象缺失了必要的方法。结合你的代码和环境,这里有几个可行的解决方案:

方案1:升级PyInstaller到兼容版本

你当前使用的PyInstaller 4.1是比较旧的版本(发布于2021年),对Python 3.8和pywin32的兼容性可能存在问题。升级到较新的PyInstaller版本可以解决很多这类依赖打包问题:

pip install --upgrade pyinstaller

升级完成后,重新使用原打包命令尝试:

pyinstaller --onefile --console test.py

方案2:添加隐藏导入参数

如果升级后问题依然存在,可以通过PyInstaller的--hidden-import参数强制包含pywin32的相关依赖模块,确保打包时不会遗漏:

pyinstaller --onefile --console --hidden-import pywintypes --hidden-import win32timezone test.py

这样可以告诉PyInstaller手动包含这些可能被自动分析忽略的模块,保证pywintypes.datetime对象拥有完整的方法。

方案3:修改代码中的时间转换逻辑

另一种思路是显式使用Python标准库的datetime模块处理时间转换,避免依赖pywintypes.Time的隐式转换逻辑,这样可以绕过缺失方法的问题:

import pywintypes, win32file, win32con, ntsecuritycon
import os
import datetime

def changeFileCTime(fname, createdNewtime):
    # 显式将时间戳转换为带时区的datetime对象
    dt = datetime.datetime.fromtimestamp(createdNewtime, datetime.timezone.utc)
    wintime = pywintypes.Time(dt)
    winfile = win32file.CreateFile(fname, ntsecuritycon.FILE_WRITE_ATTRIBUTES, 0, None, win32con.OPEN_EXISTING, 0, None)
    win32file.SetFileTime(winfile, wintime, None, None)
    winfile.close()

def main():
    filename = input("File to copy creation time from: ")
    ctime = os.path.getctime(filename)
    filename = input("File to set ctime to: ")
    changeFileCTime(filename, ctime)

if __name__ == '__main__':
    main()

这种方式通过标准库明确处理时间的时区信息,减少了对pywin32内部转换逻辑的依赖,打包后更稳定。

建议先尝试方案1,因为版本兼容性是这类问题最常见的原因,如果不行再依次尝试方案2和3。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:57:39