python自建日历表格

📅 2026/7/4 9:46:24
python自建日历表格
日期星期、月份、季度、是否周末是否月末、每月第一天等信息import pandas as pd import datetime import calendar import numpy as np datepd.date_range(2024-01-01,2024-12-31,freqD) # print(date) date_str[i.strftime(%Y-%m-%d) for i in date] # print(date_str) week[int(i.strftime(%w)) for i in date] #0表示星期日 # print(week) week_desc[] def week_desc_info(): for i in week: if i 0: week_desc.append(星期日) elif i1: week_desc.append(星期一) elif i 2: week_desc.append(星期二) elif i3: week_desc.append(星期三) elif i 4: week_desc.append(星期四) elif i5: week_desc.append(星期五) elif i6: week_desc.append(星期六) return week_desc week_descweek_desc_info() month[i.strftime(%m) for i in date] month_desc[str(int(i))月 for i in month] season[int(np.floor((int(i)2.9)/3)) for i in month] season_desc[第str(i)季度 for i in season] dayofyear[int(i.strftime(%j)) for i in date] #一年中的第几天 weekofyear[int(i.strftime(%W)) for i in date] #一年中第几周U也是周w从1到7u从0到6描述每周的星期 weekend[] def is_weekend_flag(): for i in week: if i0 or i6: weekend.append(1) else: weekend.append(0) return weekend weekendis_weekend_flag() #是否月末 month_end[] def is_month_lastday(): for i in date: _,days_in_monthcalendar.monthrange(i.year,i.month) day_of_monthint(i.strftime(%d)) if day_of_monthdays_in_month: month_end.append(1) else: month_end.append(0) return month_end month_endis_month_lastday() # month_end[calendar.monthrange(i.year,i.month)[1:] for i in date] month_first_day[datetime.date(i.year,i.month,1) for i in date] datedfpd.DataFrame({riqi:date_str,星期:week,星期中文:week_desc,月份:month,月份中文:month_desc,季度:season,季度中文:season_desc,天:dayofyear, 周:weekofyear,是否周末:weekend,是否月末:month_end,月的第一天:month_first_day}) print(datedf.head(10)) print(datedf.tail(10)) datedf.to_excel(/Users/kangyongqing/Downloads/日历str(datetime.date.today()).xlsx,indexFalse)查看并保存日历到本地import calendar calcalendar.calendar(2024,2,1,6,4) print(cal) print(type(cal)) with open(/Users/kangyongqing/Downloads/未命名.txt,w,encodingutf-8) as file: file.write(cal)2,1,6,4为控制展示格式间距可以适当调整。使用with语句是一个好习惯因为它会在执行完代码块后自动关闭文件。