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

Python中如何为datetime生成的变量添加.xlsx扩展名

解决用datetime生成唯一Excel文件名的问题

核心问题处理:生成带.xlsx的合法唯一文件名

你当前用str(current_dateTime) + ".xlsx"的写法语法上可行,但存在隐藏问题:datetime.now().isoformat()生成的字符串包含冒号(例如2024-05-20T14:35:22.123),而Windows系统不允许文件名包含冒号,会导致保存失败。推荐两种可靠写法:

方法1:用strftime自定义格式(推荐)

直接生成无非法字符且带扩展名的文件名,精确到微秒保证唯一性:

output_file = datetime.now().strftime("%Y-%m-%d_%H-%M-%S_%f.xlsx")

方法2:替换isoformat中的非法字符

如果坚持使用isoformat,先替换掉冒号等非法字符再追加扩展名:

current_dateTime = datetime.now().isoformat().replace(":", "-").replace(".", "_")
output_file = f"{current_dateTime}.xlsx"

代码其他问题修正

你的代码还存在循环缩进错误、数据列数不匹配表头的问题,以下是完整修正后的代码:

from spire.pdf.common import *
from spire.pdf import *
import os
import openpyxl
from openpyxl import load_workbook
from datetime import datetime
import xlsxwriter

# 生成合法的唯一Excel文件名(推荐方法1)
output_file = datetime.now().strftime("%Y-%m-%d_%H-%M-%S_%f.xlsx")

pdf = PdfDocument()
pdf.LoadFromFile("c:/Documents/Projects/file.pdf")
pdf.SaveToFile("excel/template.xlsx", FileFormat.XLSX)
pdf.Close()

folder = 'excel'

output_wb = openpyxl.Workbook()
output_sheet = output_wb.active
output_sheet.title = 'Bearskin'

cells = ['BQ34', 'G13', 'J22']

# 修复循环缩进,遍历所有Excel文件
for filename in os.listdir(folder):
    if filename.endswith('.xlsx'):
        file_path = os.path.join(folder, filename)
        workbook = openpyxl.load_workbook(file_path)
        values = [workbook.active[cell].value for cell in cells]
        # 补空值匹配表头6列,避免数据错位
        values += [""] * 3
        output_sheet.append(values)

# 插入表头行
output_sheet.insert_rows(1)

output_sheet['A1']= "Section"
output_sheet['B1']= "Operation"
output_sheet['C1']= "Depth"
output_sheet['D1']= "Duration"
output_sheet['E1']= "Cumulative Hours"
output_sheet['F1']= "Cumulative Days"

output_wb.save(output_file)

关键说明

  • 文件名唯一性:两种方法都包含微秒级时间戳,确保每次生成的文件名不重复。
  • 跨系统兼容性:替换冒号或用strftime避免了Windows/macOS/Linux的文件名非法字符限制。
  • 循环修正:原代码循环体未缩进,只会处理最后一个Excel文件,修正后遍历所有目标文件。
  • 列数匹配:原cells仅3个单元格,表头有6列,补充空值避免数据与表头错位。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:44:53