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

Python如何将datetime时间写入日志文件?报错TypeError求解

问题原因

你的代码报错是因为字符串格式化逻辑错误:

  • '\n'.join(bot_log)生成的字符串里没有任何占位符(比如%s),但你后续用%运算符传入了时间戳参数,Python找不到插入参数的位置,因此抛出not all arguments converted during string formatting错误。
  • 另外bot_log中的空字符串元素会导致日志出现无效空行,不符合记录需求。
修复方案

要实现「时间戳在日志消息前方」的需求,需要给每条有效日志条目添加时间戳前缀后再写入文件。以下是修正后的代码:

from pathlib import Path
import datetime

# 仅保留有效日志消息,无需空字符串
bot_log = ["Set up the file path thingy"]
# 生成时间戳(如需每条日志用不同时间,可移到循环内)
timestamp = datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)")

with open('bot.log', 'a') as f:
    # 给每条消息添加时间戳前缀,再用换行符连接
    formatted_logs = [f"{timestamp} - {msg}" for msg in bot_log]
    f.write('\n'.join(formatted_logs) + '\n')  # 末尾加换行保证每条日志独立一行
额外优化建议

如果后续需要记录更多类型的日志,建议直接使用Python标准库的logging模块,它原生支持时间戳、日志级别、多线程安全等功能,比手动写文件更稳定可靠:

import logging

# 配置日志格式:时间戳-日志级别-日志内容
logging.basicConfig(
    filename='bot.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%d-%b-%Y (%H:%M:%S.%f)'
)

# 记录日志
logging.info("Set up the file path thingy")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 03:10:48