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

在pandas中能否为Word文档同一占位符交替设置strftime()格式?

在Pandas中实现日期格式交替输出

当然可以实现,下面是具体的操作思路和代码示例:

1. 生成交替格式的标记列

先给DataFrame添加一个标记列,用来区分每行对应的日期格式,用numpy.tile就能快速生成循环的标识:

import pandas as pd
import numpy as np

# 构造示例数据
df = pd.DataFrame({
    "date": pd.date_range(start="2024-01-01", periods=5),
    "content": ["行1内容", "行2内容", "行3内容", "行4内容", "行5内容"]
})

# 生成交替标记:0对应格式"(%y %m %d)",1对应格式"(%d %m %y)"
df["format_flag"] = np.tile([0, 1], len(df)//2 + 1)[:len(df)]

2. 定义格式转换函数并应用

写一个自定义函数,根据标记值选择对应的strftime格式,再通过apply函数批量处理日期列:

def alternate_date_format(date, flag):
    if flag == 0:
        return date.strftime("(%y %m %d)")
    else:
        return date.strftime("(%d %m %y)")

# 生成格式化后的日期列
df["formatted_date"] = df.apply(lambda x: alternate_date_format(x["date"], x["format_flag"]), axis=1)

3. 替换Word文档占位符

最后用python-docx库把处理好的格式化日期插入到Word文档的对应占位符中:

from docx import Document

doc = Document("你的模板文档.docx")

# 假设文档中的占位符为{{date_placeholder}}
for para in doc.paragraphs:
    if "{{date_placeholder}}" in para.text:
        # 按行遍历DataFrame,替换并插入内容
        for idx, row in df.iterrows():
            para.insert_paragraph_before(f"{row['content']} {row['formatted_date']}")
        para.text = ""  # 删除原占位符段落

doc.save("生成的目标文档.docx")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 05:12:01