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

Pandas导出年度CSV时转换Date_Time为%d/%m/%Y %H:%M格式报错如何解决

报错原因

dt是pandas专为datetime类型的单列(Series对象)提供的访问器,你筛选pd_mean[years == year_X]得到的是多列的DataFrame对象,直接调用dt属性必然会触发AttributeError。

解决方案

推荐直接用to_csv自带的date_format参数实现需求,不需要修改原DataFrame的结构,仅需调整导出的一行代码即可:

for year_X in range(years.min(), years.max()+1):
    print(f"Creating file (1 hr) for the year: {year_X}")
    print(pd_mean[years == year_X])
    # 仅修改这一行,通过date_format参数指定datetime列的导出格式
    pd_mean[years == year_X].to_csv(f"data_(1hr)_year_{year_X}.csv", date_format='%d/%m/%Y %H:%M')

如果需要提前把Date_Time列转换为指定格式的字符串再做其他处理,可以单独操作该列:

for year_X in range(years.min(), years.max()+1):
    print(f"Creating file (1 hr) for the year: {year_X}")
    temp_df = pd_mean[years == year_X].copy()
    # 仅对Date_Time单列调用dt.strftime
    temp_df['Date_Time'] = temp_df['Date_Time'].dt.strftime('%d/%m/%Y %H:%M')
    print(temp_df)
    temp_df.to_csv(f"data_(1hr)_year_{year_X}.csv")

内容的提问来源于stack exchange,提问作者Sultry T.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:45:06