Python实现农历生日自动提醒:从数据查询到企业微信推送

拾光
拾光
发布时间:2026-10-16| 5人浏览过
原创

本文介绍如何使用Python结合zhdate库实现农历生日自动提醒功能。通过安装依赖、创建数据库存储用户信息,利用zhdate将农历日期转换为阳历并计算距今天数。当生日临近或当天时,系统自动组装消息并通过企业微信Webhook机器人推送提醒,解决每年农历对应阳历日期变化的痛点。

在中国,许多人习惯庆祝农历生日,通常借助日历工具将农历日期转换为对应的阳历日期,并以该阳历日期作为庆祝日。

这一做法存在一个常见痛点:每年的农历生日所对应的阳历日期并不固定,每年都在变化。

本文将演示如何使用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))
...

以上就是一文教你利用Python制作一个生日提醒的详细内容,更多关于Python生日提醒的资料请关注本站其它相关文章!

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。