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

如何使用Python将表格中非finished状态数据记录为带时间戳的日志文件

问题原因

  1. 列名大小写不匹配:原表列名为Col2,现有代码用了小写的col2,会导致筛选逻辑失效
  2. 直接将整个DataFrame对象传入日志方法,logging会将整个表的输出内容作为单条消息处理,只会生成一个时间戳,无法实现每行对应一个时间戳的需求
  3. 没有指定asctime的输出格式,默认时间格式不符合你的预期

解决代码

import pandas as pd
import logging

# 筛选Col2不为finished的行,单独处理NaN值的匹配逻辑
tab_not_finished = df[(df['Col2'] != 'finished') | df['Col2'].isna()]

# 配置日志参数,指定时间格式
logging.basicConfig(
    filename='log.log',
    encoding='utf-8',
    format='%(asctime)s %(message)s',
    datefmt='%m/%d/%Y %I:%M:%S %p',
    level=logging.WARNING
)

# 逐行输出日志
for _, row in tab_not_finished.iterrows():
    col2_val = row['Col2'] if pd.notna(row['Col2']) else 'NaN'
    log_content = f"{row['Col1']} {col2_val} {row['Col3']}"
    logging.warning(log_content)

说明

  • datefmt参数里的格式符完全匹配你需要的月/日/年 12小时制时间 AM/PM的时间格式
  • 遍历处理每一行数据,确保每条记录都单独生成带时间戳的日志
  • 对Col2的空值做了专门转换,输出的NaN字符串和你预期的格式一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:27:02