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

如何将DataFrame存储为以datetime.now()为文件名的CSV文件

解决方案

你当前代码不生效的核心原因是:路径字符串中的{0}占位符没有绑定实际替换值,Python会直接将其作为普通字符写入文件名,不会自动替换为动态时间。

你可以按照以下步骤实现需求:

  • 导入datetime模块,生成符合文件名规则的时间字符串,注意不能包含:、/等Windows系统禁止出现在文件名中的特殊字符
  • 把生成的时间字符串代入路径占位符完成格式化,再调用to_csv方法保存文件

代码示例1(适配你原有str.format写法)

from datetime import datetime
import pandas as pd

# 生成格式化时间字符串,示例格式为 年月日_时分秒,无非法字符
current_time = datetime.now().strftime('%Y%m%d_%H%M%S')
# 替换路径中的{0}占位符为时间值
save_path = r'C:\Masterarbeit\werte_df{0}.csv'.format(current_time)
# 保存CSV
werte_df.to_csv(save_path, sep=',')

代码示例2(Python3.6+ 更简洁的f-string写法)

from datetime import datetime
import pandas as pd

current_time = datetime.now().strftime('%Y%m%d_%H%M%S')
# 直接在字符串中插入时间变量
werte_df.to_csv(fr'C:\Masterarbeit\werte_df{current_time}.csv', sep=',')

如果需要调整时间的显示格式,修改strftime方法内的格式符即可,比如将格式符改为%Y-%m-%d就会生成2024-05-20格式的日期字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:54:04