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

如何实现Python按月份循环从数据库拉取数据并生成对应文件

按月循环拉取数据并生成对应文件的解决方案

直接把需要处理的月份日期和对应的文件名简称一一配对,用循环逐个处理即可,完全适配你分批拉取的需求,修改后的代码如下:

核心修改后的代码

import pandas as pd
import datetime

print(datetime.datetime.now())

# 定义月份日期与对应简称的配对列表,确保顺序一一对应
month_data = [
    ('2022-01-31', 'jan'),
    ('2022-02-28', 'feb'),
    ('2022-03-31', 'mar'),
    # 按需添加更多月份,比如('2022-04-30', 'apr')
]

# 遍历每一组月份数据
for month_date, month_name in month_data:
    # 拉取当月数据(复用你的SQL逻辑,替换参数为当前循环的日期)
    sql = pd.read_sql(
        '''select col1, col2, col3 from schema.table where table.asofdate = to_date(:month, 'YYYY-MM-DD')''',
        sql_engine, 
        params={'month': month_date}
    )
    
    # 生成对应文件名和sheet名,替换为当前循环的简称
    file_path = fr'\\desktop\output\output_{month_name}.xlsx'
    writer = pd.ExcelWriter(file_path, engine='xlsxwriter')
    sql.to_excel(writer, sheet_name=f'{month_name}_recon', index=False)
    writer.close()
    
    # 打印进度信息,方便跟踪
    print(f"{month_name}月份数据已导出完成,当前时间:{datetime.datetime.now()}")

print(datetime.datetime.now())

关键说明

  • 用元组列表绑定日期和简称,避免手动修改时出现顺序错乱的问题
  • 循环内自动替换SQL参数、输出文件名、sheet名,完全不需要手动逐个修改
  • 保留了你原有的打印时间逻辑,还新增了单月完成的进度提示,方便排查问题

扩展优化(可选)

如果需要处理的月份很多,手动输入日期太麻烦,可以用pandas自动生成月末日期:

import pandas as pd
import datetime

# 设置需要处理的年份和时间范围
year = 2022
start_date = datetime.date(year, 1, 1)
end_date = datetime.date(year, 12, 31)

# 自动生成每个月的最后一天日期字符串
month_dates = pd.date_range(start=start_date, end=end_date, freq='M').strftime('%Y-%m-%d').tolist()
# 自动生成对应的月份小写简称(jan/feb/mar...)
month_names = [date.strftime('%b').lower() for date in pd.date_range(start=start_date, end=end_date, freq='M')]

# 配对成循环用的列表
month_data = list(zip(month_dates, month_names))

用这段代码替代手动定义的month_data,就能一键生成全年的月份配对数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:30:20