Python实现数据库导出Excel并动态化sql时间
import pandas as pd
import pymssql
from datetime import datetime
import time
start_time = time.time()
print("程序开始时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start_time)))
time_on = input('请输入开始时间:')
time_c = input('请输入结束时间:')
time_on = datetime.strptime(time_on, '%Y-%m-%d')
time_c = datetime.strptime(time_c, '%Y-%m-%d')
conn = pymssql.connect(server='192.168.0.101', user='sa', password='mmxyz@01234560', database='YD')
ZNZW = f"select * from View_ZZZJ_GD_ONLY WHERE cast([时间] as date) BETWEEN '{time_on}' AND '{time_c}'"
ZNZW = pd.read_sql(ZNZW, conn)
print("保存数据中...")
month_on = time_on.strftime('%m')
day_on = time_on.strftime('%d')
day_c = time_c.strftime('%d')
ZNZW.to_excel(f'归档-{month_on}{day_on}-{day_c}日.xlsx', sheet_name='0', index=False, header=True)
print("成功导出")
end_time = time.time()
print("程序结束时间:", time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end_time)))
run_time = end_time - start_time
print("程序运行耗时:%0.2f" % run_time, "s")