python自建日历表格
📅 2026/7/4 9:49:37
👁️ 阅读次数
📝 编程学习
日期,星期、月份、季度、是否周末,是否月末、每月第一天等信息
import pandas as pd import datetime import calendar import numpy as np date=pd.date_range('2024-01-01','2024-12-31',freq='D') # 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 i==1: week_desc.append('星期一') elif i == 2: week_desc.append('星期二') elif i==3: week_desc.append('星期三') elif i == 4: week_desc.append('星期四') elif i==5: week_desc.append('星期五') elif i==6: week_desc.append('星期六') return week_desc week_desc=week_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到7,u从0到6描述每周的星期 weekend=[] def is_weekend_flag(): for i in week: if i==0 or i==6: weekend.append(1) else: weekend.append(0) return weekend weekend=is_weekend_flag() #是否月末 month_end=[] def is_month_lastday(): for i in date: _,days_in_month=calendar.monthrange(i.year,i.month) day_of_month=int(i.strftime('%d')) if day_of_month==days_in_month: month_end.append(1) else: month_end.append(0) return month_end month_end=is_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] datedf=pd.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',index=False)查看并保存日历到本地:
import calendar cal=calendar.calendar(2024,2,1,6,4) print(cal) print(type(cal)) with open('/Users/kangyongqing/Downloads/未命名.txt','w',encoding='utf-8') as file: file.write(cal)2,1,6,4为控制展示格式间距,可以适当调整。
使用with语句是一个好习惯,因为它会在执行完代码块后自动关闭文件。
编程学习
技术分享
实战经验