如何从指定数据表提取日期并按当日拆分生成对应CSV文件
实现按当日日期拆分数据的修改方案
核心逻辑调整
- 先获取当前MST时区的当日纯日期,避免时区偏差导致的日期判断错误
- 逐行遍历SQL返回结果,提取
AppointmentDateTime字段转换为纯日期格式,和当日日期做比对 - 分别存入两个结果列表后,导出为两个独立的CSV文件
完整修改后的代码
import os import csv from datetime import date, datetime import dateutil.tz # 原有数据库连接依赖保留即可,此处省略你原有的cnxn初始化逻辑 cur = cnxn.cursor() query = """ SELECT A.CaseNumber,A.AppointmentDateTime,A.AppointmentType,A.AppointmentInterviewType,B.ClientInfoData FROM ASPEN.tbl_Appointment A LEFT JOIN ASPEN.tbl_ClientInfo B ON A.CaseNumber = B.CaseNumber ORDER BY B.CaseNumber, B.ClientInfoSortOrder """ cur.execute(query) rows = cur.fetchall() # 获取MST时区当日纯日期,和原代码时区保持一致 mst = dateutil.tz.gettz('US/Mountain') today = datetime.now(tz=mst).date() # 初始化两个结果列表,分别存储当日之前、当日之后的数据 before_today_rows = [] after_today_rows = [] # 逐行判断拆分 for row in rows: # AppointmentDateTime为查询结果第二个字段,索引为1,字段顺序调整时需同步修改此处索引 appt_date = row[1].date() if row[1] is not None else None # 空预约日期的处理逻辑可按需调整,此处默认归入当日之前分类 if not appt_date: before_today_rows.append(row) continue if appt_date < today: before_today_rows.append(row) # 如需将当日数据归入某一类,直接调整判断条件即可,例如>=today就是把当日算入之后的分类 elif appt_date > today: after_today_rows.append(row) # 分别导出两个CSV文件 bucket_name = os.environ['BUCKET_NAME'] # 导出当日之前的数据 before_file_path = '/tmp/before_today_appointment.csv' with open(before_file_path, 'w', newline='', encoding='utf-8') as fp: writer = csv.writer(fp) # 可选:取消下方注释写入表头,导出的CSV会自带列名更便于使用 # writer.writerow(['CaseNumber','AppointmentDateTime','AppointmentType','AppointmentInterviewType','ClientInfoData']) writer.writerows(before_today_rows) # 导出当日之后的数据 after_file_path = '/tmp/after_today_appointment.csv' with open(after_file_path, 'w', newline='', encoding='utf-8') as fp: writer = csv.writer(fp) # writer.writerow(['CaseNumber','AppointmentDateTime','AppointmentType','AppointmentInterviewType','ClientInfoData']) writer.writerows(after_today_rows)
注意事项
- 若数据库返回的
AppointmentDateTime字段本身就是date类型而非datetime类型,直接去掉.date()转换即可 - 代码中新增的
newline=''参数,可避免Windows系统下CSV出现多余空行的问题
内容的提问来源于stack exchange,提问作者Bard Gaming
相关产品推荐
相关产品推荐

