Python实现农历生日自动提醒:从数据查询到企业微信推送
本文介绍如何使用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生日提醒的资料请关注本站其它相关文章!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













