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

将含datetime.datetime键的字典写入CSV时遇AttributeError问题求助

问题分析与解决办法

这个错误的根源其实很明确:你使用csv.DictWriter的writerow()方法时,传入的是字典的键(也就是datetime.datetime对象),而不是DictWriter期望的、和fieldnames对应结构的字典。因为for data in csvdict这个循环默认只会遍历字典的键,不是完整的键值对数据,自然会触发'datetime.datetime' object has no attribute 'keys'的错误。

下面给你两种可行的解决思路:

方案1:构造符合DictWriter要求的字典结构

遍历字典的键值对,把每个datetime键转换成可读性强的日期字符串,再组装成和csv_columns匹配的字典,传给writerow():

import csv
from datetime import datetime

csv_columns = ['Date','Fund Value']
csvdict = {datetime(2019, 1, 16, 0, 0): '2.8010', datetime(2019, 2, 8, 0, 0): '2.8295'}
bof = 'your_output_file.csv'

try:
    # 加上newline=''避免Windows下出现空行,是csv模块的推荐写法
    with open(bof, 'w', newline='') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=csv_columns)
        writer.writeheader()
        # 遍历字典的键值对而不是单独的键
        for date_obj, fund_value in csvdict.items():
            # 将datetime对象转为自定义格式的字符串,这里用YYYY-MM-DD,你可以按需调整
            date_str = date_obj.strftime('%Y-%m-%d')
            # 构造符合fieldnames的字典
            writer.writerow({'Date': date_str, 'Fund Value': fund_value})
except IOError:
    print("I/O error")

方案2:改用普通csv.writer更直接

如果觉得构造字典有点繁琐,也可以用基础的csv.writer,直接写入列表格式的行数据:

import csv
from datetime import datetime

csv_columns = ['Date','Fund Value']
csvdict = {datetime(2019, 1, 16, 0, 0): '2.8010', datetime(2019, 2, 8, 0, 0): '2.8295'}
bof = 'your_output_file.csv'

try:
    with open(bof, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(csv_columns) # 写入表头
        for date_obj, fund_value in csvdict.items():
            date_str = date_obj.strftime('%Y-%m-%d')
            writer.writerow([date_str, fund_value])
except IOError:
    print("I/O error")

额外注意点

  • 一定要把datetime对象转换成字符串再写入CSV:CSV是纯文本格式,直接写入datetime对象会得到类似datetime.datetime(2019, 1, 16, 0, 0)的原始对象字符串,完全不符合可读的日期格式。你可以用strftime()自定义格式,或者用date_obj.isoformat()生成标准ISO日期字符串。
  • 代码里的newline=''是官方文档推荐的写法,能避免Windows系统下写入CSV时自动插入空行的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 22:04:06