网络编程
位置:首页>> 网络编程>> Python编程>> 用python自动生成日历

用python自动生成日历

作者:yongjiliu  发布时间:2022-08-28 14:28:58 

标签:python,日历
目录
  • 效果

  • 特点

  • 使用手册

  • 主要代码

  • 完整项目地址

效果

用python自动生成日历

用python自动生成日历

在Excel日历模板的基础上,生成带有农历日期、节假日、休班等信息的日历,解决DIY日历最大的技术难题。

图中日期,第一行为公历,第二行为节假日,第三行为农历,第四行是其他特别的日子,比如生日、纪念日等。

特点

  • 使用门槛低

Python + Excel,会运行Python脚本,会使用Excel即可上手。

  • 步骤简单

只需要修改Excel的年份(在一月份表头修改),运行一次脚本

  • 可扩展

可制作任意年份的日历(修改年份即可)

  • 可定制

可以添加其他特殊日期

使用手册

第一步,修改日历年份及样式

打开calendar.xlsx文件,在一月份表头,”输入年份“位置,修改样式

第二步,添加自定义日期

calendar.xlsx文件的生日栏,添加需要标注的日期,并保存

第三部,运行脚本

主要代码

BdDataFetcher.py


#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import datetime
import logging
import time

import requests
import re
import json

class BdDataFetcher(object):
   def __init__(self):
       self.url = 'https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php'
       self.request_session = requests.session()
       self.request_session.headers = {
           "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36",
           "Accept": "application/json, text/plain, */*",
           "Accept-Encoding": "gzip, deflate",
           "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
           "Connection": "keep-alive"
       }

def request(self, year_month):
       payload = {
           'query': year_month,
           'resource_id': 39043,
           't': int(round(time.time() * 1000)),
           'ie': 'utf8',
           'oe': 'utf8',
           'cb': 'op_aladdin_callback',
           'format': 'json',
           'tn': 'wisetpl',
           'cb': 'jQuery110206747607329442493_1606743811595',
           '_': 1606743811613
       }
       resp = self.request_session.get(url=self.url, params=payload)
       logging.debug('data fetcher resp = {}'.format(resp.text))
       bracket_pattern = re.compile(r'[(](.*?)[)]', re.S)
       valid_data = re.findall(bracket_pattern, resp.text)
       json_data = json.loads(valid_data[0])
       almanac = json_data['data'][0]['almanac']
       result = {}
       for day in almanac:
           key = '{}-{}-{}'.format(day['year'], day['month'],day['day'])
           result[key] = day
       return result
if __name__ == '__main__':
   logging.basicConfig(level=logging.DEBUG,
                       format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                       datefmt='%a, %d %b %Y %H:%M:%S')
   BdDataFetcher().request('2021年1月')

ExcelDateFiller.py


#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import logging
import os
import sys
from copy import copy

import openpyxl
import pandas as pandas
import xlrd
import xlutils
import yaml
from pandas._libs.tslibs.timestamps import Timestamp

from BdDataFetcher import BdDataFetcher

class Config(object):
   def __init__(self, config_path):
       try:
           with open(config_path, "r", encoding="utf-8") as yaml_file:
               data = yaml.load(yaml_file)
               self.excel_path = data['excel_path']
               self.sheet_special = data['sheet_special']
               self.skip_row = data['date_skip_row']
               self.skip_col = data['date_skip_col']
               self.max_length = data['max_length']
               self.holiday_color = data['holiday_color']
               self.workday_color = data['workday_color']
               logging.basicConfig(level=logging.DEBUG,
                           format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                           datefmt='%a, %d %b %Y %H:%M:%S')

except Exception as e:
           logging.error(repr(e))
           sys.exit()

class SpecialDay(object):
   def __init__(self):
       self.is_lunar = False
       self.desc = ''

class ExcelDateFiller(object):
   def __init__(self):
       self.data_fetcher = BdDataFetcher()
       self.target = os.path.splitext(config.excel_path)[0] + '_out' + os.path.splitext(config.excel_path)[-1]
       # try:
       #     shutil.copy(config.excel_path, self.target)
       # except IOError as e:
       #     print("Unable to copy file. %s" % e)
       # except:
       #     print("Unexpected error:", sys.exc_info())
       # self.target_workbook = openpyxl.load_workbook(self.target, data_only=True)

def fill_date_with_openpyxl(self):
       for sheet in self.target_workbook.worksheets:
           for column_index in range(1, sheet.max_column):
               for row_index in range(1, sheet.max_row):
                   data = sheet.cell(column=column_index, row=row_index)
                   print(data.value)

def read_with_xlrd(self):
       workbook = xlrd.open_workbook(self.target)
       for sheet in workbook.sheets():
           for column_index in range(0, sheet.ncols):
               for row_index in range(0, sheet.nrows):
                   data = sheet.cell(rowx=row_index, colx=column_index)
                   logging.debug('ctype = {}, value = {}, xf_index = {}'.format(data.ctype, data.value, data.xf_index))

def write_with_openpyxl(self):
       target_workbook = openpyxl.load_workbook(self.target)
       sheet = target_workbook.get_sheet_by_name('sheet_name')
       sheet.cell(0, 0).value = 'value'
       target_workbook.save()

def write_with_xlwt(self):
       workbook = xlrd.open_workbook(self.target)
       workbook = xlutils.copy(workbook)
       sheet = workbook.get_sheet(0)
       sheet.write(0, 0, 'value')
       workbook.save()

def load_special_sheet(self):
       data = {}
       special_sheet = pandas.read_excel(config.excel_path, sheet_name=config.sheet_special, header=0)
       for row_index in range(special_sheet.shape[0]):
           key = special_sheet.iloc[row_index, 0]
           struct_time = pandas.to_datetime(key.timestamp(), unit='s').timetuple()
           key = '{}-{}'.format(struct_time.tm_mon, struct_time.tm_mday)
           value = SpecialDay()
           value.desc = special_sheet.iloc[row_index, 1]
           value.is_lunar = special_sheet.iloc[row_index, 2] == '是'
           data[key] = value
       return data

def fill_date(self):
       pandas_workbook = pandas.read_excel(config.excel_path, sheet_name=None, skiprows= config.skip_row, keep_default_na=False)
       out_workbook = openpyxl.load_workbook(config.excel_path)

special_day = self.load_special_sheet()

day_data = {}
       for sheet_name in pandas_workbook.keys():
           if not sheet_name.endswith('月'):
               continue
           sheet = pandas_workbook.get(sheet_name)
           out_sheet = out_workbook.get_sheet_by_name(sheet_name)

nrows = sheet.shape[0]
           ncols = sheet.shape[1]
           for row_index in range(nrows):
               for col_index in range(ncols):
                   data = sheet.iloc[row_index, col_index]
                   logging.debug('origin row = {}, col = {}, data = {}'.format(row_index, col_index, data))
                   if type(data) == Timestamp:
                       struct_time = pandas.to_datetime(data.timestamp(), unit='s').timetuple()
                       date = '{}-{}-{}'.format(struct_time.tm_year, struct_time.tm_mon, struct_time.tm_mday)
                       if not day_data.__contains__(date):
                           request_data = self.data_fetcher.request(year_month='{}年{}月'.format(struct_time.tm_year, struct_time.tm_mon))
                           day_data.update(request_data)

temp_row = row_index + 2 + config.skip_row
                       temp_col = col_index + 1
                        # weekend color
                       if day_data[date]['cnDay'] == '六' or day_data[date]['cnDay'] == '日':
                           holiday_font = copy(out_sheet.cell(temp_row, temp_col).font)
                           holiday_font.color = config.holiday_color
                           out_sheet.cell(temp_row, temp_col).font = holiday_font
                       # holiday color
                       if day_data[date].__contains__('status'):
                           if day_data[date]['status'] == '1': # 休假
                               holiday_font = copy(out_sheet.cell(temp_row, temp_col).font)
                               holiday_font.color = config.holiday_color
                               out_sheet.cell(temp_row, temp_col).font = holiday_font
                           if day_data[date]['status'] == '2': #班
                               workday_font = copy(out_sheet.cell(temp_row, temp_col).font)
                               workday_font.color = config.workday_color
                               out_sheet.cell(temp_row, temp_col).font = workday_font
                       lunar_date = day_data[date]['lDate']
                       if lunar_date == '初一':
                           lunar_date = '{}月'.format(day_data[date]['lMonth'])
                       # logging.debug('date = {}, value = {}'.format(str(date), lunar_date))
                       temp_content = ''
                       if day_data[date].__contains__('value'):
                           temp_content += day_data[date]['value']
                           if len(temp_content) > config.max_length:
                               temp_content = temp_content[:config.max_length]
                       temp_content += '\n'
                       temp_content += lunar_date
                       # spacial day
                       month_day = day_data[date]['month'] + '-' + day_data[date]['day']
                       if special_day.__contains__(month_day):
                           temp_special_day = special_day.get(month_day)
                           if not temp_special_day.is_lunar:
                               temp_content += '\n'
                               temp_content += temp_special_day.desc

lunar_month_day = day_data[date]['lunarMonth'] + '-' + day_data[date]['lunarDate']
                       if special_day.__contains__(lunar_month_day):
                           temp_special_day = special_day.get(lunar_month_day)
                           if temp_special_day.is_lunar:
                               temp_content += '\n'
                               temp_content += temp_special_day.desc

temp_row = row_index + 3 + config.skip_row
                       temp_col = col_index + 1
                       out_sheet.cell(temp_row, temp_col).value = temp_content

out_workbook.save(filename=self.target)
       out_workbook.close()

if __name__ == '__main__':
   config = Config(config_path='config.yaml')
   date_filler = ExcelDateFiller()
   date_filler.fill_date()

完整项目地址

https://github.com/yongjiliu/diycalendar

calendar_out.xlsx为处理好的日历

来源:https://github.com/yongjiliu/diycalendar

0
投稿

猜你喜欢

  • 1.如果客户端和服务器端的连接需要跨越并通过不可信任的网络,那么就需要使用SSH隧道来加密该连接的通信。2.用set password语句来
  • 原型:EventManager是一个重要的原型,它用来赋予对象自定义事件的能力当对象类型的原型继承EventManager时,对象具有定义、
  • 随着JS与XHTML的应用普及,越来越多的web界面应用技术出现在网站上,比如我们常见的日历控件,搜索下拉框等,这些web界面应用技术大大的
  • 导读我们在使用selenium打开google浏览器的时候,默认打开的是一个新的浏览器窗口,而且里面不带有任何的浏览器缓存信息。当我们想要爬
  • 应该是开心网(kaixin.com)的宠物功能又升级了,这几次发来的邮件内容不仅不能让我开心,反而让我觉得很恶心。开心网注册也一段时间了,之
  • Django 分页功能的实现,供大家参考,具体内容如下创建项目创建APP,添加APP这些就不在多说我们这次重点来看到视图函数下面是路由设置视
  • 做一个将本地图片上传到mysql数据库的小实例,顺便也下载下来到桌面检测是否上传成功。在写代码之前得先在数据库中建立image表,用来存储图
  • 背景:pony是公司的首席体验官、首席产品经理。这次在产品峰会上pony将自己平时经验的积累与大家交流,体验较细。这次分享研发管理部,设计中
  • 在浏览天极RSS订阅页面时,可以看到天极网为方便用户定制站点内容而设立的各个RSS频道。浏览者通过订阅不同的RSS(可同时订阅多个网站),就
  • 字体的处理在网页设计中无论怎么强调也不为过,毕竟网页使用来传递信息的,而最经典最直接的信息传递方式就是文字,所以,了解一点字体的基本知识对于
  • 4. 选择最有效率的表名顺序(只在基于规则的优化器中有效)ORACLE的解析器按照从右到左的顺序处理FROM子句中的表名,因此FROM子句中
  • 最近人工智能等多门课需要复现论文,近两年的论文很多都是基于Pytorch环境做的实验,所以,这里总结一下Pytorch的安装教程,做好最快、
  • 本文实例讲述了Python大数据之从网页上爬取数据的方法。分享给大家供大家参考,具体如下:myspider.py  :#!/usr
  • 一、输出指令ASP的输出指令<% =expression %>显示表达式的值。这个输出指令等同于使用Resp
  • (以下内容部分内容参考了http://adomas.org/javascript-mouse-wheel/ )之前js 仿Photoshop
  • 炸金花题目很简单:就是自己写一个程序,实现诈金花游戏的发牌、判断输赢。规则:一付扑克牌,去掉大小王,每个玩家发3张牌,最后比大小,看谁赢。牌
  • JSON 基础简单地说,JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,
  • 主要是运用java.util.regex类。 import java.util.regex.Matcher;import java
  • 本文研究的主要是Python subprocess模块的相关内容,具体如下。在学习这个模块前,我们先用Python的help()函数查看一下
  • 主键表的主键(primary key,主关键字)是表中的一个或多个字段,它的值用于惟一地标识表中的某一条记录。一个表不能有多个主关键字,并且
手机版 网络编程 asp之家 www.aspxhome.com