5 分钟,教你用 Python 制作一个生日提醒!

Source

f1dcc854b919f834e04d6739744f1985.jpeg

大家好,我是安果!

在国内,大部分人都是过农历生日,然后借助日历工具获取农历日期对应的阳历日期,以这一天来过生!

这里还有一个痛点,即:每一年的农历生日对应的阳历日期都不一样

本篇文章将教你利用 Python 制作一个简单的生日提醒

1. 实战

具体操作步骤如下

1-1  安装依赖

# 安装依赖
pip3 install zhdate

pip3 install pymysql

其中,zhdate 模块用于中国农历、阳历之间的转换,并且支持日期差额计算

项目地址:

https://github.com/CutePandaSh/zhdate

1-2  创建数据表

创建一条数据表

create table birthday
(
    id        int auto_increment
        primary key,
    name      varchar(100)  not null comment '名称',
    yl_birth  varchar(100)  not null comment '阴历生日',
    remark    varchar(100)  null comment '备注',
    is_delete int default 0 null comment '0:正常  1:删除'
)
    comment '生日';

然后,将需要提醒用户的姓名、农历生日等数据写入

PS:这里阴历生日格式是 mm-dd,比如:10-25

1-3  查询数据

import pymysql

class Birth(object):
    def __init__(self):
        self.db = pymysql.connect(host='**',
                                  user='root',
                                  password='**',
                                  database='xag')
        self.cursor = self.db.cursor()

    def __get_births(self):
        # 获取所有数据
        self.cursor.execute("""
                             select name,yl_birth,remark from birthday where is_delete=0;""")

        datas = list(self.cursor.fetchall())

1-4  遍历,获取距离今天的天数

遍历上面的数据,将阴历转为阳历,然后计算出距离今天的天数

from zhdate import ZhDate

...
  def __get_diff(self, birth):
        """
        根据农历生日,获取当前日期距离的时间(天)
        :param birth: 农历生日,格式:10-25
        :return:
        """
        # 1、获取今日的农历日历
        now = str(datetime.now().strftime('%Y-%m-%d')).split("-")
        # 年、月、日
        year, month, day = int(now[0]), int(now[1]), int(now[2])

        # 1、获取阴历生日,转为阳历
        birth_month = int(birth.split("-")[0].strip())
        birth_day = int(birth.split("-")[-1].strip())
        birth_ying = ZhDate(year, birth_month, birth_day)

        # 转为阳历
        birth_yang = birth_ying.to_datetime()

        # 2、计算距离当前日期的时间间隔(天)
        today = datetime.now().strftime('%Y-%m-%d')
        d1 = datetime.strptime(today, '%Y-%m-%d')

        diff_day = (birth_yang-d1).days
        return diff_day

...
 # 遍历数据
        for item in datas:
            name = item[0]
            birth = item[1]
            nickname = item[2]
            diff = self.__get_diff(birth)
...

1-5  组装数据及消息推送

通过时间间隔,在提前一周、生日当天做一个提醒

最后,将组装好的消息通过企业微信机器人发送出去

import requests
import json

...
   def send_wechat(self, msg: str):
        """发送信息到企业微信"""
        # 这里填写你的机器人的webhook链接
        url = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key**'
        headers = {"Content-Type": "text/plain"}
        data = {
            "msgtype": "text",
            "text": {
                "content": msg
            }
        }
        # 发送消息
        requests.post(url, headers=headers, data=json.dumps(data))
...

2. 最后

我已经将文中的源码上传到公众号后台,回复关键字 birth 获取完整的源码!

推荐阅读

5 分钟,教你从零快速编写一个油猴脚本!

爬虫工具篇 - 必会用的 6 款 Chrome 插件

小技巧 | Chrome 插件如何完成剪切板的操作!

END

好文和朋友一起看~